I define a class with abstract type as follow:
abstract class AbsCell2{
type T
val init: T
private var value: T = {
println("Hello "+init);
init
}
def get : T = value
def set(x : T) = { value = x}
}
Now I instantiate an object with type Int
scala> val cell = new AbsCell2{type T = Int ; val init = 10}
Hello 0
cell: AbsCell2{type T = Int} = $anon$1@969ebb
Pay attention to the output from println. It seams the variable init hasn’t been initialized as 10. Note that the version of scala is 2.9.0-1
I think you’re looking for Scala’s early initializers,
Early initializers allow you to allocate a new object and set some specific fields before the class constructor runs. In this case, since
valuedepends oninit, we use the early initializer syntax (new { val init = ... } with AbsCell2) to first setinitso that the class constructor can properly initializevalue.See also this question: In Scala, what is an "early initializer"?