Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static const in Kotlin from Java class name

I usually have this in Java:

package some.package;
public class Clz {
    public static final String ACTION_DIVE = Clz.class.getName() + ".action.DIVE";
}

that is accessible from outside that class as Clz.ACTION_DIVE and the value will be "some.package.Clz.action.DIVE".

How can I do the same in Kotlin class Clz so that it can be accessed in the same way from outside Java classes? I tried the following but it does not compile because it is not a constant:

package some.package
object Clz {
    const val ACTION_DIVE = Clz.javaClass.name + ".action.DIVE"
}
like image 845
Randy Sugianto 'Yuku' Avatar asked May 12 '16 09:05

Randy Sugianto 'Yuku'


2 Answers

Clz::class.java.name

See Class references in the official Kotlin documentation.

like image 54
Alexander Udalov Avatar answered Sep 21 '22 03:09

Alexander Udalov


You can use:

object Clz {
    val ACTION_DIVE = Clz::class.java.name + ".action.DIVE"
}

Notice that since it's calling java extension property the ACTION_DIVE may not be const.

If you really needed a const you can do you could, in older versions of Kotlin compiler, do:

object Clz {
    const val ACTION_DIVE = "" + Clz::class + ".action.DIVE"
}
like image 20
miensol Avatar answered Sep 20 '22 03:09

miensol