私は暗黙の変換を実験してきましたが、これらを使用する「enrich-my-libray」パターンについて十分に理解しています。基本的な暗黙の理解と暗黙の証拠の使用を組み合わせようとしました...しかし、以下の方法で示すように、私は何か重要なことを誤解しています:
import scala.language.implicitConversions
object Moo extends App {
case class FooInt(i: Int)
implicit def cvtInt(i: Int) : FooInt = FooInt(i)
implicit def cvtFoo(f: FooInt) : Int = f.i
class Pair[T, S](var first: T, var second: S) {
def swap(implicit ev: T =:= S, ev2: S =:= T) {
val temp = first
first = second
second = temp
}
def dump() = {
println("first is " + first)
println("second is " + second)
}
}
val x = new Pair(FooInt(200), 100)
x.dump
x.swap
x.dump
}
上記の方法を実行すると、次のエラーが発生します。
Error:(31, 5) Cannot prove that nodescala.Moo.FooInt =:= Int.
x.swap
^
私のスコープ内の暗黙的な変換は、Int を FooInt に、またはその逆に変換できるという十分な「証拠」になると思っていたので、私は困惑しています。これについて私をまっすぐに設定してくれてありがとう!
アップデート:
以下のピーターの優れた答えに混乱しなかった後、APIで暗黙の証拠を使用したいという正当な理由の1つに電球がつきました。この質問に対する私自身の回答で詳しく説明します(以下も)。