I am defining my Users SQLite database table, and to do so, I have created the following UserContract and UserEntry classes:
class UserContract private constructor(){
class UserEntry private constructor(): BaseColumns {
companion object {
val TABLE_NAME = "users"
val COLUMN_DISPLAY_NAME = "display_name"
val COLUMN_EMAIL = "email"
//...
}
}
}
The problem I am facing is that I cannot access _ID property provided by BaseColums implementation:
val columnDisplayName = UserContract.UserEntry.COLUMN_DISPLAY_NAME //It is OK
val columnId = UserContract.UserEntry._ID //Unresolved reference: _ID
The equivalent code in Java works fine, so, does anybody knows what would be the reason or where the mistake is?
You can only access it using BaseColumns._ID
since it's a Java interface defining a constant.
On Kotlin, a companion object is an actual object with inheritance, whereas in java a class with static methods does not really behave like an object.
For instance, if you had BaseColumns
as a kotlin class instead of a java interface, you could have done something like:
open class KBaseColumns {
val _ID = "_id"
}
class UserContract private constructor(){
class UserEntry private constructor(): BaseColumns {
companion object : KBaseColumns() {
val TABLE_NAME = "users"
val COLUMN_DISPLAY_NAME = "display_name"
val COLUMN_EMAIL = "email"
}
}
}
object Example {
fun someMethod() {
val id = UserContract.UserEntry._ID
}
}
Where _ID
is accessible in this case because the companion object is actually a subclass of KBaseColumns
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