Kotlin | Keep Annotation
What does @Keep
companion object mean in Kotlin?
In Kotlin, the @Keep
annotation prevents a class, object, or function from being removed by proguard. This is useful if a particular piece of your code is necessary for debugging or analysis, or if it would cause unexpected behavior if removed by proguard.
A companion object
is an object that contains the static members of a class. These members can be accessed before any instances of the class are created.
When @Keep
and companion object
are used together, it ensures that the static members are not removed by proguard. This is useful if you need to access the static members from other classes, or if the static members are necessary for debugging or analysis.
@Keep
companion object MyCompanion {
val myStaticVariable = "Hello World!"
fun myStaticFunction() {
println(myStaticVariable)
}
}
In this code, the MyCompanion
object is marked with the @Keep
annotation. This means that it will not be removed by proguard. The myStaticVariable
and myStaticFunction
members are also static members of the MyCompanion
object. These members can be accessed before an instance of the MyCompanion
object is created.
Use Cases:
- When you need to access static…