Search code examples
scalageneric-programmingcovariant

Override Generic Functions in Scala With "method xxx overrides nothing" Error


I am learning Scala language features. I declare a class with a type parameter.

class Pair[+T](val first: T, val second: T){
  // T is a covariant type. So an invariance R is introduced.
  def replaceFirst[R >: T](newFirst: R) = {
    new Pair(newFirst, second)
  }

  override def toString = "(" + first + ", " + second + ")"
}

Class Pair has a generic function replaceFirst. I declare a new class NastyDoublePair which extends Pair[Double]. And I'd like to override the generic function replaceFirst. Here is the compile error code:

class NastyDoublePair(first: Double, second: Double) extends Pair[Double](first, second){
  override def replaceFirst(newFirst: Double): Pair[Double] = {
    new Pair[Double](newFirst, second)
  }
}

The compile error is below

Ch17.scala:143: error: method replaceFirst overrides nothing.
Note: the super classes of class NastyDoublePair contain the following, non final members named replaceFirst:
def replaceFirst[R >: Double](newFirst: R): ch17.p9.Pair[R]
            override def replaceFirst(newFirst: Double): Pair[Double] = {
                                     ^

However, if I change the function replaceFirst to

def replaceFirst(newFirst: T) = {
  new Pair(newFirst, second)
}

besides, change the Pair[+T] to Pair[T]. Everything goes well.

How can I fix the compile error, even if I'd like to set type parameter T to a covariant type. Otherwise, there is no solution to my case. I must use an invariant type parameter, not Pair[+T] but Pair[T]

Thanks for sharing your idea. Best wishes.


Solution

  • This happens because the type parameters change in NastyDoublePair, you can make this compile like follows:

    class NastyDoublePair(first: Double, second: Double) extends Pair[Double](first, second){
      override def replaceFirst[R >: Double](newFirst: R) = {
        new Pair(newFirst, second)
      }
    }