Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access companion object used in kotlin class after enabling proguard

I have a Kotlin class with some variables in companion object. After enabling proguard, The variables are not getting accessed.

class Test{    
    ......    
    companion object {    
        const val USER_NAME = "user_name"    
        .....    
  }    
  .....    
}  

Proguard rules include:-

-keep class kotlin.** { *; }    
-keep class kotlin.Metadata { *; }    
-dontwarn kotlin.**    
-keepclassmembers class **$WhenMappings {    
    <fields>;    
}    
-keepclassmembers class kotlin.Metadata {    
    public <fields>;    
    public <methods>;    
}    

-keepclassmembers class * {    
    static final % *;    
    static final java.lang.String *;    
}    
like image 786
Surbhi Aggarwal Avatar asked Nov 28 '18 13:11

Surbhi Aggarwal


People also ask

How do you use the companion object in Kotlin?

To create a companion object, you need to add the companion keyword in front of the object declaration. The output of the above code is “ You are calling me :) ” This is all about the companion object in Kotlin. Hope you liked the blog and will use the concept of companion in your Android application.

Does ProGuard work on Kotlin?

In Android, the common tools are ProGuard and more recently, R8. This means that you can run ProGuard on your Kotlin app and everything should work as intended without crashing.

Can a Kotlin data class have companion object?

The companion object can be declared within an existing class and the functions or parameters can be defined inside the companion object declaration. As you can see above, we can declare a companion object inside an existing class.


1 Answers

Problem resolved using @Keep before companion object

class Test{    
    ......    
    @Keep companion object {    
        const val USER_NAME = "user_name"    
        .....    
  }    
  .....    
}  
like image 161
Surbhi Aggarwal Avatar answered Oct 19 '22 23:10

Surbhi Aggarwal