我正在学习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]。
谢谢你分享你的想法。谨致问候。
发布于 2017-07-10 15:00:51
之所以会发生这种情况,是因为NastyDoublePair中的类型参数发生了变化,您可以按照如下方式进行编译:
class NastyDoublePair(first: Double, second: Double) extends Pair[Double](first, second){
override def replaceFirst[R >: Double](newFirst: R) = {
new Pair(newFirst, second)
}
}https://stackoverflow.com/questions/45015181
复制相似问题