Scala:“类需要是抽象的,因为方法没有定义"错误 [英] Scala: "class needs to be abstract, since method is not defined" error
问题描述
我熟悉此错误消息,但在这种情况下我不太确定:
I'm familiar with this error message but I'm not quite sure about it in this case:
class Foo extends A {
// getting error here
}
trait A extends B {
def something(num:Int):Boolean = {
num == 1
}
}
trait B {
def something[S](num:S):Boolean
}
但这编译得很好:
class Foo extends A ...
trait A extends B[Int] {
def something(num:Int):Boolean = {
num == 1
}
}
trait B[S] {
def something(num:S):Boolean
}
完全错误:class Foo 需要是抽象的,因为未定义类型 [S](num: S)Boolean 的 trait A 中的方法
第一个不应该编译吗?我在这里做错了什么,我该如何解决?
Shouldn't the first compile? What am I doing wrong here and how can I fix it?
推荐答案
def something(num:Int):Boolean
和 def something[S](num:S):Boolean
有不同的方法签名.第一个的参数类型是Int
.第二个的参数类型是泛型 S
.
def something(num:Int):Boolean
and def something[S](num:S):Boolean
have different method signatures. The argument type of the first is Int
. The argument type of the second is the generic S
.
class Foo extends A {
// You have to implement this abstract method
// that is inherited from B via A.
def something[S](num:S):Boolean = ???
}
trait A extends B {
def something(num:Int):Boolean = {
num == 1
}
}
trait B {
def something[S](num:S):Boolean
}
想象一下试图调用从 B
继承的 something[S](num:S)
方法:
Imagine trying to call the something[S](num:S)
method inherited from B
:
new Foo().something[String]("x")
如果您可以不实施它,您希望会发生什么?
If you could get away with not implementing it, what would you expect to happen?
在第二个例子中,由于A
继承了B[Int]
,类泛型S
绑定到Int
,所以A
继承的方法是something(num:Int)
,与实现的方法有相同的签名.
In the second example, since A
inherits B[Int]
, the class generic S
is bound to Int
, so the method that A
inherits is something(num:Int)
, which does have the same signature as the implemented method.
这篇关于Scala:“类需要是抽象的,因为方法没有定义"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!