这编译:
import scala.collection._
trait Foo[A, +This <: SortedSet[A] with SortedSetLike[A,This]]
extends SortedSetLike[A, This] { this: This =>
def bar: This = (this: SortedSetLike[A,This]).empty
}
但是如果删除了向上转换,它就无法编译:
import scala.collection._
trait Foo[A, +This <: SortedSet[A] with SortedSetLike[A,This]]
extends SortedSetLike[A, This] { this: This =>
def bar: This = this.empty
}
为什么?来自
extends
条款我们知道Foo
是 SortedSetLike[A, This]
,所以向上转换当然是有效的 - 但这不表明编译器允许发生冲突的继承吗?
最佳答案
SortedSetLike trait 从 继承了空方法SetLike .
/** The empty set of the same type as this set
* @return an empty set of type `This`.
*/
def empty: This
但是排序集 覆盖空方法并具有显式返回类型:
/** Needs to be overridden in subclasses. */
override def empty: SortedSet[A] = SortedSet.empty[A]
由于您指定了 此 是 的子类排序集 编译器会找到 排序集 的 empty first 的实现,它返回一个 排序集 .编译器不知道如何转换结果 排序集 给您的 此 子类。
但是如果你向上看 SortedSetLike trait 编译器会找到它的空方法,它返回一个 此 .
关于scala - 为什么在这个 Scala 代码中需要向上转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31080332/