Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Java interface static fields in Kotlin

Tags:

kotlin

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!

like image 258
pt2121 Avatar asked Feb 09 '16 17:02

pt2121


People also ask

CAN interfaces have static fields Java?

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.

CAN interface have static fields?

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).

How do I call a static function in Kotlin?

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.

How do I set static value in Kotlin?

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.


1 Answers

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.

like image 152
hotkey Avatar answered Nov 03 '22 17:11

hotkey