Reputation: 472
I'd like to do something like this:
case class D[X <: A](arg1 : X, arg2: Int) extends X {
}
D is kind of a decorator class for arg1, and I'd like to apply it to several different kinds of things that are subclasses of A.
However I get this error:
scala> case class D[X <: A](arg1 : X, arg2: Int) extends X { override val name = "D"; } :6: error: class type required but X found
If not, is there a more scalaish way to do this kind of thing?
Upvotes: 1
Views: 430
Reputation: 32345
The class that you extend has to be known at compile time and a type parameter is generally not. Therefore, it's not possible to do this.
However, if you're trying to extend X
to benefit from the implementations of methods defined in an interface trait A
, then you can mix-in X
when instantiating the class.
new D with X
If you'd like to preserve the 'case class' features of D
, then using D
as a proxy which forwards calls to methods defined in A
to the parameter arg1
of type X
is one solution.
trait A {
def foo
}
case class D[X <: A](arg1: X) extends A {
def forw = arg1
def foo = forw.foo
}
Upvotes: 1