What is the equivalent of const val of koltin in J...
# getting-started
h
What is the equivalent of const val of koltin in Java?
y
Copy code
public static final int abc = 10;
j
The
final
keyword.
h
Isn’t val equivalent to final keyword or
Copy code
public static final int abc = 10;
y
val is equivalent to final keyword. Just giving example of const val abc = 10
j
If you use final on primitive types, it's equivalent to const val.
e
primitive or String
💯 3
h
ok thanks
e
in Kotlin,
Copy code
val foo = getHello()
const val bar = "hello"
mean two different things. in Java,
Copy code
static final String foo = getHello();
always means the first, and
Copy code
static final String bar = "hello";
always means the second. Java does not have a straightforward way to express (non-
const
)
val baz = "Hello"
with a constant expression
y
exactly const is a reserved keyword in Java, but it doesn't mean final class is a const class, but it a sealed class which cannot be inherited. Same for any variable.
e
const
is a keyword in Java which is never used anywhere (same as
goto
). Java's
final
doesn't mean
sealed
(that's what the new
sealed
keyword means). Java's
final
, when applied to a class or method, means the same as it does in Kotlin (just with different defaults).
y
though it cannot be inherited but...
e
sealed class
does not mean "no inheritance", it means "closed inheritance"
final
does mean "no inheritance"
y
"though it cannot be inherited but..." - talking about final class only
y
In java there is no val but they do have var, you can use Lombok to get the ability to use val. so val is final var
a
lets also not forget that
const val
in kotlin gets inlined by the compiler at the call site, while
static final String
has no guarantee of being inlined
e
it is guaranteed if it is a constant, as per JLS
the fact that it's so hard to control this aspect of your public API/ABI is definitely a mark against Java though