Scala 无法证明类型相等

标签 scala types

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

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 参数应该相同。为什么不是这样?

最佳答案

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
}

关于Scala 无法证明类型相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17166085/

相关文章:

android - Sbt LibGdx : Build chain hangs in packaging step

scala - Akka Stateful Actor 跨节点复制

Haskell:接受类型参数并根据该类型返回值的函数?

scala - 从 RDD 中随机获取一个元素

scala - 使用 Scala 调度库禁用 SSL

c++ - 从 Type* 转换为 Type,反之亦然

types - OpenCL 内核中的自定义类型

java - 如何格式化 servlet 响应以生成 HTML 中 "accept"参数可接受的媒体类型?

haskell - 带有约束的类型列表

scala - 重命名 Spark DataFrame 中的嵌套结构列