Constants
Since everything in Java is an object (unless you're a primitive type), we're used to putting all the constants inside our objects as static members.
And since Kotlin has companion objects, we usually try putting them there:
class MyClass { companion object { val MY_CONST = "My Const" } }
This will work, but you should remember that companion object is an object, after all.
So, this will be translated to the following code, more or less:
public final class Spock { @NotNull private static final String MY_CONST = "My Const"; public static final Spock.Companion Companion = new Spock.Companion(...); public static final class Companion { @NotNull public final String getMY_CONST() { return MyClass.MY_CONST; } private Companion() { } } }
And the call to our constant looks like this:
String var1 = Spock.Companion.getSENSE_OF_HUMOR(); System.out.println(var1);
So, we have our class, Spock
, inside of which we have another class. But what we wanted was only static final String
.
Let's...