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 ) }
source share