A `const val` 1) optimizes the generated bytecode ...
# getting-started
f
A
const val
1) optimizes the generated bytecode 2) can be used in annotations. My question: are there any other benefits over just using
val
that I am missing?
k
Does it really "optimize" bytecode? It does inline it but isn't the JVM able to do that for most properties anyway? I'd try to find some benchmarks before stating things about performance.
But I think you've got everything.
f
a normal top-level val has a getter and a setter
I don't know if that makes much difference
k
I think optimizing getters and setters is the main job of the JVM simple smile
f
then the only benefit thats left is the use in annotations?
k
It's what the docs say about it too.
f
would you say there is a benefit for the developer when using
const val
as opposed to a
val
that contains a literal constant?
it is less likely that someone accidentally assigns a non-constant value, right?
I have no real-world experience, that's why I ask if this is a useful safeguard in real projects
in my imagination, a
val
, even if it was supposed to contain immutable data, could be accidentally assigned to a non-constant value (at declaration point)
k
They're both non-reassignable, so there's no safety difference.
f
you change the initial assignment tho
k
What do you mean?
f
you can change the value right at the declaration point
k
Yeah of course, but that's for both right?
f
right but const enforces String or primitives
I thought that this might be a useful safeguard
const will show a warning, val will not
k
Hmm maybe, but it's not like you often have a choice between a primitive and something else.
f
I could for example assign a return value from a function call that isn't actually fixed, right?
I could accidentally do
val CONSTANT_NUMBER = getRandomNumber()
as an extreme example
k
Hmm yeah I see what you mean.
But still, it's going to be constant for the duration of the program.
f
yea that's true
it could be a computed property tho but I guess this doesn't just happen "accidentally"
I think it still makes sense because it expresses intention
after all, someone could change a val to a var because the thinks thats okay
but when he sees
const
it's pretty obvious that this is not meant to be a var ever
or am I wrong?
l
Yeah, different opinions, that’s personal I guess
f
Well I've never worked as a programmer so I have to think myself into these situations
l
Well, usually if I see a
val
, I won’t change it to
var
, regardless of it having
const
or not 🙂