Scala:"类需要是抽象的,因为方法没有定义"错误

goo*_*goo 2 scala

我熟悉这个错误信息,但在这种情况下我不太确定:

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
}
Run Code Online (Sandbox Code Playgroud)

但这编译很好:

    class Foo extends A ...

    trait A extends B[Int] {
       def something(num:Int):Boolean = {
          num == 1
       }
    }

    trait B[S] {
      def something(num:S):Boolean
    }
Run Code Online (Sandbox Code Playgroud)

完整错误: class Foo needs to be abstract, since method something in trait A of type [S](num: S)Boolean is not defined

不应该先编译吗?我在这里做错了什么,我该如何解决?

Chr*_*tin 8

def something(num:Int):Booleandef something[S](num:S):Boolean有不同的方法签名.第一个的参数类型是Int.第二种的参数类型是泛型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
}
Run Code Online (Sandbox Code Playgroud)

想象一下尝试调用something[S](num:S)继承自的方法B:

new Foo().something[String]("x")
Run Code Online (Sandbox Code Playgroud)

如果你没有实现它可以逃脱,你会发生什么?

在第二个示例中,由于A继承B[Int],类泛型S被绑定Int,因此A继承的方法something(num:Int)与实现的方法具有相同的签名.