Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access to BaseColumns provides _ID property in Kotlin

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?

like image 641
AlexTa Avatar asked Jun 03 '17 18:06

AlexTa


1 Answers

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

like image 166
Logain Avatar answered Nov 07 '22 00:11

Logain