why scala don't allow define lazy val in trait?

Viewed 871

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?

1 Answers

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

Related