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?
val evaluates when defined. def evaluates on every call, so performance could be worse than val for multiple calls. You'll get the same performance with a single call. And with no calls you'll get no overhead from def , so you can define it even if you will not use it in some branches.
In Scala the general rule is that you should always use a val field unless there's a good reason not to. This simple rule (a) makes your code more like algebra and (b) helps get you started down the path to functional programming, where all fields are immutable.
def is the keyword you use to define a method, the method name is double , and the input parameter a has the type Int , which is Scala's integer data type.
There are three ways of defining things in Scala: def defines a method. val defines a fixed value (which cannot be modified) var defines a variable (which can be modified)
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
}
The val
is evaluated once and stored in a field. The def
is implemented as a method and is reevaluated each time, but does not use memory space to store the resulting value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With