【问题标题】:Scala Cannot prove type equalityScala无法证明类型相等
【发布时间】:2013-06-18 10:05:40
【问题描述】:

我正在定义一个可操作的类型:

trait Operable {
  def +[A](other: A)(implicit evidence: this.type =:= A): this.type
  def -[A](other: A)(implicit evidence: this.type =:= A): this.type
  def *[A](other: Float): this.type
}
/** Position descriptions */
trait Pos[T <: Operable] {
  def eval: T
}
def test[T <: Operable](x1: Pos[T], x2: Pos[T]): T = {
  x2.eval - x1.eval
}

我得到以下编译时错误:

 Cannot prove that _1.type =:= T.

为什么编译器不能证明类型相等,如何克服这个问题? x1 和 x2 的 T 参数应该相同。为什么不是这样?

【问题讨论】:

  • 我认为 Régis 给你的答案(使用 F 有界多态性)是可行的方法,但值得注意的是编译器会对 &lt;:&lt; 而不是 =:= 感到满意。跨度>

标签: scala types


【解决方案1】:

this.type 是特定实例的类型。它与任何其他实例不兼容,即使是完全相同类型的实例。 所以基本上在这个定义中:

def -[A](other: A)(implicit evidence: this.type =:= A): this.type

您的证据试图证明 otherthis 完全相同,这可能不是您的想法。

我想你会想要重新设计你的设计。您可以尝试使用 F 有界多态性:

trait Operable[Self <: Operable[Self]] {
  def +(other: Self): Self
  def -(other: Self): Self
  def *(other: Float): Self
}
/** Position descriptions */
trait Pos[T <: Operable[T]] {
  def eval: T
}
def test[T <: Operable[T]](x1: Pos[T], x2: Pos[T]): T = {
  x2.eval - x1.eval
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多