Scala allows you to make early definitions like so:
trait A {
val v: Int
}
class B extends { val v = 4 } with A
What is an example use of this feature?
Scala allows you to make early definitions like so:
trait A {
val v: Int
}
class B extends { val v = 4 } with A
What is an example use of this feature?
Let's see a example from the Programming in Scala book (page 451). If we have a definition like this:
Then numerArg and denomArg are called abstract vals & the trait can be used directly without extends, like this:
Or
The above two are both valid Pre-initializing of abstract val in trait, except that when you need to put an expression value to abstract vals, you can only use the later form, like this:
Another interesting example in book is to Pre-initialized fields in a class definition.
In unit tests in particular, you are interested on testing traits in isolation. In this case, you need to create an Object mixed in with the trait you are interested. This is an example:
Another scenario is when your trait depends on injected variables:
Whenever the value is used for the trait initialization. So for eaxmple for this trait:
The parameter is used to substitute for a constructor parameter. However the parameter should be rather made an abstract method, because it leaves more free space to the implementer.