Search code examples
scalagenericsconstructortype-parameterabstract-type

scala class constructors and abstract types


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?


Solution

  • You're pretty much forced to use generic type parameters in that case. You can work around it by declaring the type outside the class but then you'd need to instantiate the wrapper and then the object and it would get ugly pretty quickly.

    trait FooDef {
      type T
      class Foo(val x: T)
    }
    val ifd = new FooDef { type T = Int }
    val ifoo = new ifd.Foo(5)
    val sfd = new FooDef { type T = String }
    val sfoo = new sfd.Foo("hi")
    def intFoos(f: fd.Foo forSome { val fd: FooDef {type T = Int} }) = f.x + 1