Does using `const val` instead of `val` in a `comp...
# announcements
j
Does using
const val
instead of
val
in a
companion object
triggers any compilation/bytecode optimisation ?
s
You can look at bytecode yourself, actually
If you write a quick kotlin file and use a
const val
you’ll see that the compiler inserts the value (inlines) where the variable is used, kinda almost like a C macro if you’re familiar
💯 1
this is also why vals need to be const if you want to use them in annotations
j
So this cause a better memory usage, right? I think java compiler optimise static literals...
g
Not memory, val generates field and getter and called on runtime to get value, const val is inlined on compile time and generates only static field
j
So is the method count smaller when using
const val
?
k
Yes, no getters will be generated.
g
Also, because constants are inlined, it allows compiler do some optimizations for code where constant is used