Can I reference Java interface fields from Kotlin? I have this Java interface:
public interface BaseColumns {
public static final String _ID = "_id";
public static final String _COUNT = "_count";
}
And I implement it in Kotlin:
object UserEntry : BaseColumns {
// some code
}
I get Unresolved reference when I try UserEntry._ID
. How can I access the _ID
? Am I missing something? Thanks!
Interface variables are static because java interfaces cannot be instantiated on their own. The value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned.
No you cannot have non-static variables in an interface. By default, All the members (methods and fields) of an interface are public. All the methods in an interface are public and abstract (except static and default).
In order to implement a static method in Kotlin, we will take the help of "companion objects". Companion objects are the singleton objects whose properties and functions are tied to a class but not to the instance of that class. Hence, we can access them just like a static method of the class.
In Kotlin, you have the const keyword that's equal to the static keyword in Java. The const keyword is used to create a variable that's known to Kotlin before the compilation, so you don't need to create an instance of a class to use it.
In Kotlin, unlike Java, static members of interfaces are not derived and cannot be called in subclasses without qualifying the interface name.
You should reference _ID
through BaseColumns
: BaseColumns._ID
will work.
This seems to be different for classes: non-qualified name of a base class static member resolves to it, but the member is still not inherited.
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