How to initialize the value from trait in subtype?
scala, traits
Solution
One way to do this is to delay evaluation of `u` by using `def` or `lazy val` as follows:
trait T {
def t = 3
def u = 1::t::Nil
}
class U extends T {
override def t = 2
}
(new U).u
or
trait T {
val t = 3
lazy val u = 1::t::Nil
}
class U extends T {
override val t = 2
}
(new U).u
The differences are as follows:
- `val` makes an expression evaluate during initialization
- `def` makes an expression evaluate each time `u` is used
- `lazy val` makes it evaluated on first `u` usage and caches the result
Problem
If I write : ``` trait T { val t = 3 val u = 1::t::Nil } class U extends T { override val t = 2 } (new U).u ``` it shows this. ``` List(1, 0) ``` How should I change the above code to make it display the following: ``` List(1, 2) ``` i.e. `override val t` sets the value of `t` for `u` in the trait `T`?