为什么在此Scala代码中必须进行向上转换? [英] Why is upcasting necessary in this Scala code?

查看:96
本文介绍了为什么在此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

}

但是如果取消了上流,则无法编译:

But if the upcast is removed it fails to compile:

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子句中我们知道FooSortedSetLike[A, This],因此向上转换当然是有效的-但是这不表明编译器允许发生冲突的继承吗?

Why? From the extends clause we know that Foo is a SortedSetLike[A, This], so the upcast is valid of course - but doesn't this show that the compiler has allowed conflicting inheritance to occur?

推荐答案

SortedSetLike 特性从 SetLike 继承了 empty 方法. >

The SortedSetLike trait inherits the empty method from SetLike.

/** The empty set of the same type as this set
* @return  an empty set of type `This`.
*/
def empty: This

但是 SortedSet 会覆盖 empty 方法,并且具有显式的返回类型:

But SortedSet overrides the empty method and has an explicit return type:

/** Needs to be overridden in subclasses. */
override def empty: SortedSet[A] = SortedSet.empty[A]

由于您指定 SortedSet 的子类,因此编译器将找到 SortedSet empty 首先,它返回一个 SortedSet .编译器不知道如何将结果 SortedSet 转换为您的 This 子类.

Since you specify that This is a subclass of SortedSet the compiler will find SortedSet's implementation of empty first, which returns a SortedSet. The compiler does not know how to convert the resulting SortedSet to your This subclass.

但是,如果您转换为 SortedSetLike 特性,则编译器将找到其 empty 方法,该方法返回 This .

But if you upcast to the SortedSetLike trait the compiler will find its empty method which returns a This.

这篇关于为什么在此Scala代码中必须进行向上转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆