Or are val
s in scala objects lazy by default?
Anyway, if it's necessary to declare a val
in an object lazy by using lazy
, is it possible to do something like
lazy object SomeObject
or (like you do in c++)
object A {
lazy:
val a
val b
...
}
Because I would like to be lazy and not have to relabel all my val
s lazy val
Vals and Lazy vals are present in Scala. lazy keyword changes the val to get lazily initialized. Lazy initialization means that whenever an object creation seems expensive, the lazy keyword can be stick before val.
A lazy val is most easily understood as a "memoized (no-arg) def". Like a def, a lazy val is not evaluated until it is invoked. But the result is saved so that subsequent invocations return the saved value. The memoized result takes up space in your data structure, like a val.
This is where the @transient lazy val pattern comes in. In Scala lazy val denotes a field that will only be calculated once it is accessed for the first time and is then stored for future reference. With @transient on the other hand one can denote a field that shall not be serialized.
Scala Language Var, Val, and Def Lazy val lazy val is a language feature where the initialization of a val is delayed until it is accessed for the first time.
To answer your first question ("are val
s in scala objects lazy by default?"): No, not exactly, but the objects themselves are kind of lazy, which may be lazy enough. From 5.4 ("Object Definitions") of the Scala language specification:
Note that the value defined by an object definition is instantiated lazily. The
new m$cls
constructor is evaluated not at the point of the object definition, but is instead evaluated the first timem
is dereferenced during execution of the program (which might be never at all).
So, for example, if we have these three objects:
object X {
val answer = { println("Here's X's answer!"); 42 }
}
object Y {
lazy val answer = { println("Here's Y's answer!"); 1 }
}
object Z extends App {
println("Here we go.")
println(X)
println(Y)
println(X.answer)
println(Y.answer)
}
Then when we run Z
, we see the following:
Here we go.
Here's X's answer!
X$@38d24866
Y$@f1aa6ce
42
Here's Y's answer!
1
So the val
in X
isn't lazy, but it's also not evaluated until the first time we use X
.
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