goo
goo

Reputation: 2280

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
}

But this compiles fine:

    class Foo extends A ...

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

    trait B[S] {
      def something(num:S):Boolean
    }

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

Shouldn't the first compile? What am I doing wrong here and how can I fix it?

Upvotes: 2

Views: 5527

Answers (1)

Chris Martin
Chris Martin

Reputation: 30736

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
}

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?

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.

Upvotes: 8

Related Questions