I'm trying to rewrite my android app on Kotlin, and I've faces problem while converting ContentProvider contract class. So I have simple contract class (default stuff like content type and content uris is omitted):
public final class Contract {
public static final class Contacts {
public static final String NAME = "Name"
public static final String BIRTH = "Birth"
public static final String IMAGE = "Image"
}
}
If I understand correctly, in Kotlin we don't have static members. Instead of this, we have "companion objects". So after converting it to Kotlin, I have this code:
object BirthdayContract {
class Contacts : BaseColumns {
companion object {
val NAME = "Name"
val BIRTH = "Birth"
val IMAGE = "Image"
}
}
}
But when I'm trying to access fields like Contract.Contacts.NAME, I have error: "NAME has private access". Changing the visibility modifiers gave no effect. So is there some way to use such contract classes in Kotlin, or it better to keep it in Java?
UPD I think that I should clarify - my caller code is also in Kotlin. The problem was in @JvmField annotation. With it, I can access static members directly, without calling getters.
NAME
is a property and by default its backing field has private access. But since it's a property, there's a getter for it: getNAME()
.
Since this is not how you naturally access constants in Java, there are a couple ways to directly expose the field:
const
: const val NAME = "Name"
@JvmField
annotation: @JvmField val NAME = "Name"
To expose constants as fields, annotate them with @JvmField
class Contacts {
companion object {
@JvmField val NAME = "Name"
@JvmField val BIRTH = "Birth"
@JvmField val IMAGE = "Image"
}
}
Then you can use them from Java like this:
String name = Contacts.NAME;
Once all of your code is in Kotlin, you can remove the @JvmField annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With