3

私は操作可能なタイプを定義しています:

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 パラメータは同じでなければなりません。そうでないのはなぜですか?

4

1 に答える 1

5

this.type特定のインスタンスのタイプです。まったく同じタイプのインスタンスであっても、他のインスタンスとは互換性がありません。したがって、基本的にこの定義では:

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

otherあなたの証拠は、 が とまったく同じインスタンスであることを証明しようとしていますがthis、これはおそらくあなたが考えていることではありません。

設計をやり直したいと思うでしょう。代わりに F-bounded polymorphism を使用してみてください:

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
}
于 2013-06-18T10:33:08.967 に答える