为什么在这个Scala代码中需要上传?
发布时间:2020-12-16 19:01:51 所属栏目:安全 来源:网络整理
导读:这编译: 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} 但是如果upcast被删除,则无法编译: import scala.
这编译:
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 } 但是如果upcast被删除,则无法编译: import scala.collection._ trait Foo[A,This] { this: This => def bar: This = this.empty } 为什么?从extends子句中我们知道Foo是一个SortedSetLike [A,This],所以upcast当然是有效的 – 但是这不表明编译器允许发生冲突的继承? 解决方法
SortedSetLike trait继承自SetLike的空方法.
/** The empty set of the same type as this set * @return an empty set of type `This`. */ def empty: This 但是SortedSet覆盖了空方法,并且具有明确的返回类型: /** Needs to be overridden in subclasses. */ override def empty: SortedSet[A] = SortedSet.empty[A] 既然你指定这是SortedSet的一个子类,编译器会发现SortedSet的空的第一个执行,它返回一个SortedSet.编译器不知道如何将生成的SortedSet转换为此子类. 但是,如果您对SortedSetLike trait表示赞同,编译器将会找到它返回一个“This”的空方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |