Matej Drobnič
05/20/2019, 8:08 AMconst
keyword existing? Why can't compiler automatically treat all vals that are assigned to constant value (such as string literal or number literal) as const
? Is there a situation where using const
is not preferred?diesieben07
05/20/2019, 8:10 AMconst
will be inlined by the compiler at the site where it is used. If you change the value, all users of your library will have to recompileMatej Drobnič
05/20/2019, 8:10 AMMatej Drobnič
05/20/2019, 8:11 AMtseisel
05/20/2019, 8:17 AMconst val
is just like static final
primitives in Java, it defines a constant that can be referenced elsewhere, so that you don't have to change all usage of the same String
or Int
litteral in your whole code when its value change.
The fact that the compiler inlines the value in the bytecode is just an optimization, but an actual field is created for the constant too so that libraries can use it if it is public.diesieben07
05/20/2019, 8:18 AMwbertan
05/20/2019, 8:18 AMconst
in the app as well. now that you spoke about it, I have a go with the decompiler, and looks weird...
class PathTest1 {
companion object {
private const val NAME = "This is a name!"
}
private fun asas1() {
println(NAME)
}
private fun asas2() {
println(NAME)
}
}
It decompiles to:
public final class PathTest1 {
private static final String NAME = "This is a name!";
public static final PathTest1.Companion Companion = new PathTest1.Companion((DefaultConstructorMarker)null);
private final void asas1() {
String var1 = "This is a name!";
System.out.println(var1);
}
private final void asas2() {
String var1 = "This is a name!";
System.out.println(var1);
}
public static final class Companion {
private Companion() {
}
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
}
And like this:
class PathTest2 {
private val NAME = "This is a name!"
private fun asas1() {
println(NAME)
}
private fun asas2() {
println(NAME)
}
}
It decompiles to:
public final class PathTest2 {
private final String NAME = "This is a name!";
private final void asas1() {
String var1 = this.NAME;
System.out.println(var1);
}
private final void asas2() {
String var1 = this.NAME;
System.out.println(var1);
}
}
diesieben07
05/20/2019, 8:18 AMconst
makes this behavior of the Java compiler a choice.diesieben07
05/20/2019, 8:18 AM