我使用类型约束来表示类型A
和B
必须相同。下面,我可以隐式转换 from A
to B
,但需要显式转换 from B
to A
。这样做的正确方法是什么?
class Pair[A, B](var first: A, var second: B) {
def swap()(implicit ev: A =:= B) {
val tmp = second
second = first
first = tmp //won't compile without appending .asInstanceOf[A]
}
/*
...other methods like replaceFirst, replaceSecond that
don't require types A, B to be the same
*/
}