我可以声明一个扩展其自己的类型参数的装饰器类吗?
我想做这样的事情:
case class D[X <: A](arg1 : X, arg2: Int) extends X {
}
D 是 arg1 的装饰器类,我想将其应用于作为 A 子类的几种不同类型的事物。
但是我收到此错误:
scala> case class D[X <: A](arg1 : X, arg2: Int) 扩展 X { override val name = "D"; } :6: 错误:需要类类型,但找到了 X
如果没有,是否有更 scalaish 的方法来做这种事情?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您扩展的类必须在编译时已知,而类型参数通常不是。因此,不可能这样做。
但是,如果您尝试扩展
X
以从接口特征A
中定义的方法的实现中受益,那么您可以混合使用X 实例化类时。
如果您想保留
D
的“case class”功能,则使用D
作为代理,将调用转发到A
中定义的方法> 到X
类型的参数arg1
是一种解决方案。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 traitA
, then you can mix-inX
when instantiating the class.If you'd like to preserve the 'case class' features of
D
, then usingD
as a proxy which forwards calls to methods defined inA
to the parameterarg1
of typeX
is one solution.