scala class constructors and abstract types

Viewed 1852

I want to use an abstract type rather than a type parameter.

In my generic classes constructor, I want to have a parameter of the generic type, but the code doesn't compile:

class SomeOtherClass(val s: S){
    type S
}

The scala compiler error is "not found: type S"

If I use a type parameter instead of an abstract type, then it works:

class SomeClass[T](val t: T){
    //...
}

Does scala force me to use a type parameter rather than an abstract type, if I want to have a generic parameter in the constructor?

Is there another way to do this?

5 Answers

None of the other answers here capture both parts of the very common pattern that is used for this situation, as below. We use either a trait or an abstract class for the SomeOtherClass (as in Luigi's answer) and then the companion object's apply method is the factory to create instances easily. It takes the s val and the type parameter S can be inferred, which simplifies instantiating the object wherever we use it.

trait SomeOtherClass {
  type S
  val something: S 
}

object SomeOtherClass {
  def apply[S0](s:S0) = new SomeOtherClass {
    type S = S0
    val something = s
  }
}

// usage
SomeOtherClass(12)
Related