[英]Unable to override an abstract method of a trait
我有一个未实现的方法特征(该特征来自第3方库,所以我无法更改)
scala> trait A {
| def B[T](b:T):T
| }
defined trait A
我正在尝试扩展它并在其中实现方法B
(已经尝试了三种方法),但出现以下错误。 我的主要要求是我想将T
B
实现为Int
(即B[Int]
并返回b*2
)
scala> class C extends A {
| def B(b:Int):Int = b*2
| }
<console>:12: error: class C needs to be abstract, since method B in trait A of type [T](b: T)T is not defined
class C extends A {
^
scala> class C extends A {
| def B[T](b:T):T = b*2 //I know why this doesn't work but how could I implement B[Int]
| }
<console>:13: error: value * is not a member of type parameter T
def B[T](b:T):T = b*2
^
scala> class C extends A {
| override def B(b:Int):Int = b*2
| }
<console>:12: error: class C needs to be abstract, since method B in trait A of type [T](b: T)T is not defined
class C extends A {
^
<console>:13: error: method B overrides nothing.
Note: the super classes of class C contain the following, non final members named B:
def B[T](b: T): T
override def B(b:Int):Int = b*2
^
scala>
原始方法应该适用于任意输入类型T
如果要实现/覆盖它,则还必须为所有可能的输入类型提供支持。
因此,如果您不支持此特性,最好不要继承它。
如果必须这样做,那么唯一的方法就是这样做:
case class C() extends A {
override def B[T](b: T): T = {
val res = b.asInstanceOf[Int] * 2
res.asInstanceOf[T]
}
}
并祈祷只会提供int值作为输入。
为了创建扩展A的具体类,您需要为A中的所有抽象方法提供一个实现。因此,在这种情况下,您需要为
def B[T](b: T):T
由于B
是泛型函数,因此您需要提供B
的泛型实现以及Int
的专业化。
def B[T](b: T): T = b
def B(b: Int): Int = b*2
编译器将对Int
值使用B
的特殊版本,对所有其他值使用通用版本。
先前的答案表明
override def B[Int](b: Int): Int = b
但是在这种情况下, Int
是类型参数,而不是 Int
数据类型,因此这是一个泛型函数,与
override def B[T](b: T): T = b
这提供了B
的具体实现,即identity
功能。 这可能不是您想要的...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.