Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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?

like image 986
khacsinhcs Avatar asked Jun 05 '19 13:06

khacsinhcs


People also ask

What is the difference between lazy Val and variable in Scala?

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.

What is the difference between @transient and @lazy in Scala?

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.

What's new in Scala 3?

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.

What is lazy Val in Java?

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.


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

like image 117
Dionysis Nt. Avatar answered Oct 16 '22 20:10

Dionysis Nt.