我正在学习 Scala 语言功能。我声明了一个带有类型参数的类。
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 + ")"
}
类Pair具有通用功能replaceFirst。我声明了一个NastyDoublePair扩展的新类Pair[Double]。而且我想覆盖通用函数replaceFirst。这是编译错误代码:
class NastyDoublePair(first: Double, second: Double) extends Pair[Double](first, second){
override def replaceFirst(newFirst: Double): Pair[Double] = {
new Pair[Double](newFirst, second)
}
}
编译错误如下
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] = {
^
但是,如果我将功能更改replaceFirst为
def replaceFirst(newFirst: T) = {
new Pair(newFirst, second)
}
此外,更改Pair[+T]为Pair[T]. 一切顺利。
T即使我想将类型参数设置为协变类型,如何修复编译错误。否则,我的情况没有解决方案。我必须使用一个不变的类型参数,不是Pair[+T]但是Pair[T]
感谢您分享您的想法。最好的祝愿。