Referring to abstract type members in class constructors in Scala

424 Views Asked by At

I can have a field referring to an abstract type member in Scala, e.g.

abstract class C {
  type T
  val t: T
}

but it seems that I cannot do the same thing for a constructor parameter:

abstract class C(t: T) { // not found: type T
  type T
}

Why?

1

There are 1 best solutions below

0
On

The first line of definition of a class is a constructor, so it is independant of a given implementation of the class (since you're building it, you cannot know the abstract type member yet).

However, what you can do is give a type parameter to your class:

abstract class C[T](c: T) {
}

So that T can be used in the constructor (which is just a type-dependant method, now). Note that type parameters and members are two different things, so you cannot do this:

val stringC = new C("foo") {}  // the {} enables instantiation of abstract classes
val other: stringC.T = "bar"

If you want to use stringC.T notation, you need to define a type member which is equal to your type parameter:

class C[A](c: A) {
  type T = A
}