What are the implications of using def
vs. val
in Scala to define a constant, immutable value? Obviously, I 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 val
final
, which can lead to better-optimised code by the VM.
A def
won'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 val
s there.
i.e. instead of
class Foo {
val MyConstant = 42
}
this:
class Foo {}
object Foo {
val MyConstant = 42
}