Scala: usage example for early definition / early initializer / pre-initialized fields

Scala allows you to make early definitions as follows:

trait A { val v: Int } class B extends { val v = 4 } with A 

What is an example of using this function?

+3
source share
3 answers

Whenever a value is used to initialize a characteristic. So, for an example of this trait:

 trait UsefulTrait { val parameter : Int private val myHelperObject = new MyExpensiveClass(parameter) } 

The parameter is used to replace the constructor parameter. However, the parameter should be more abstract, because it leaves more free space for the developer.

+2
source

See an example from programming in the Scala book (p. 451). If we have this definition:

 trait RationalTrait { val numerArg: Int val denomArg: Int } 

Then the numbers Arg and denomArg are called abstract vals, and this attribute can be used directly without extensions, for example:

 val x = new RationalTrait { val numerArg = 1 val denomArg = 2 } 

Or

 val y = new { val numerArg = 1 val denomArg = 1 } with RationalTrait 

The above two are valid. The abstract val values ​​in the attribute are pre-initialized, except that when you need to put the expression value in abstract vals , you can only use a later form , for example:

 val z = new { val numerArg = 1 * x val denomArg = 2 * x } with RationalTrait 

Another interesting example in the book is Pre-Initialized Fields in a Class Definition.

 class RationalClass(n: Int, d: Int) extends { val numerArg = n val denomArg = d } with RationalTrait { def + (that: RationalClass) = new RationalClass( numer * that.denom + that.numer * denom, denom * that.denom ) } 
+2
source

In unit tests, in particular, you are interested in testing properties individually. In this case, you need to create an object mixed with the sign of interest to you. This is an example:

 trait Display { def show(msg: String) = ... } val o = new Object with Display o.show("hey!") 

Another scenario is that your trait depends on the variables you enter:

 trait Logging { val stream: java.io.OutputStream def log(msg: String) = ... } val o = new { val stream = new FileOutputStream(...) } with Logging o.log("hey!") 
0
source

Source: https://habr.com/ru/post/1478867/


All Articles