TrN
TrN

Reputation: 1250

Method parametrized with type from a range of types in Scala?

I'd like to define a class inheritance hierarchy so a parametrized method have a parameter type from between my first base class and the current one:

class A {
 var x; 
}
class B(parent:A = null) extends A {
 var y;
 protected def method[/* T where, T is subclass of A but super class of type.this */](param:T):Unit = {}
}
class C(parent:B = null) extends B {
 var z
 protected override def method[/* T where, T is subclass of A but super class of type.this */](param:T):Unit = {}
}

Is this possible? Is there any reason that I shouldn't try to achieve that (architecture reasons or any others)?

Upvotes: 0

Views: 111

Answers (1)

senia
senia

Reputation: 38045

You could use >: this.type type bound:

class A
class B extends A
class C extends B { def method[T >: this.type <: A](a: T) = a }
class D extends C

So you can't call method on C with type parameter D:

scala> new C().method[D](new D)
<console>:12: error: type arguments [D] do not conform to method method's type parameter bounds [T >: C <: A]
              new C().method[D](new D)
                            ^

But you can call it with D type parameter on D:

scala> new D().method[D](new D)
res0: D = D@49df83b5

Note that any instance of D is also an instance of C, so new C().method(new D) (without type parameter) will be compiled as new C().method[C](new D).

Upvotes: 7

Related Questions