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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.