Access trait's class object property


#1

I'm moving my ContentProvider android codes to kotlin. These codes were converted from kotlin plugin. How to access TABLE_NAME in this codes? If i access like DataContract.Items.TABLE_NAME(as in original java codes), there will be 'Unresolved reference: TABLE_NAME' error . Better ways are welcome.

val table_name = DataContract.Items.TABLE_NAME public trait ItemsColumns {   class object {   public val TABLE_NAME: String = "items"   } }

public class DataContract() {
  class object {
  public class Items() : ItemsColumns {
           class object {
           public val TEMP: String = “temp”
           
           }
  }
  }
}


#2

The only way of accessing a class object is through the name of its containing class:

ItemsColumns.TABLE_NAME

Class objects are not inherited.


#3

Hi Andrey,

In one of my Java class, i can access TABLE_NAME like this:

DataContract.object.Items.TABLE_NAME


But from another kotlin class, it’s not possible to access TABLE_NAME using this:

DataContract.Items.TABLE_NAME


I wonder why from my Java class, i can get all inherited public properties but not from my other kotlin class.

Sorry if this is an obvious thing, but i’m still not really understand.


#4

In Java, static fields are inherited, in Kotlin they do not exist as such (only instance properties of class objects exist), and are not inherited. This is done to avoid many puzzlers described in this book: http://www.javapuzzlers.com/


#5

Thanks for the explanation and link