I try to define a trait with a lazy val
trait MyTrait {
lazy val something: Int
}
object SomeThing extends MyTrait {
override lazy val something: Int = 42
}
Then I got compile error in MyTrait
. I wonder why scala don't allow us define lazy val
in trait? How can we define lazy val
in trait?
In Scala, variables declared using the val keyword are initialized when the value is defined in the code, not when it is executed even if there is no code that calls the variable. Whereas in case of lazy val declaration of variables, they are initialized at the first call to it in the code and no variable will be created if no call is made.
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 3 implements Version 6 of the SIP-20 improved lazy vals initialization proposal. The newly proposed lazy val initialization mechanism aims to eliminate the acquisition of resources during the execution of the lazy val initializer block, thus reducing the possibility of a deadlock.
lazy val is a feature that defers the initialization of a variable, a typical pattern used in Java programs. It is also called a call by need evaluation strategy where the statement is not evaluated until its first use, meaning to postpone or defer the evaluation until demanded.
lazy in a trait does not make sense. lazy
indicates the calculation of the value only when called.
When you want to access the value of something
it is not MyTrait.something
that is going to be called but that property in your classes that extend the trait. In your case
SomeThing.something
.
You can keep the lazy
in your extending classes.
the trait only defines the necessary variables-functions that need to be overridden
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