What are the implications of using def vs. val in Scala to define a constant, immutable value? I obviously can write the following:
val x = 3;
def y = 4;
var a = x + y; // 7
What’s the difference between those two statements? Which one performs better / is the recommended way / more idiomatic? When would I use one over the other?
Assuming these are class-level declarations:
The compiler will make a
valfinal, which can lead to better-optimised code by the VM.A
defwon’t store the value in the object instance, so will save memory, but requires the method to be evaluated each time.For the best of both worlds, make a companion object and declare constants as
vals there.i.e. instead of
this: