我发现自己不止一次写下以下丑陋的模式:
class Something[A, B](implicit ev: A =:= B = null) {
...
def doStuff {
if (ev == null) ... // know that A is not the same as B
else ... // safely assume A is equal to B
}
}
更糟糕的是,当ev != null
时,我有时会写出诸如someB.asInstanceOf[A]
之类的异端。
答案 0 :(得分:6)
只需使用类型类
trait DoStuff[A, B] {
def apply(): Unit
}
trait DoStuff0 {
implicit def neDoStuff[A, B]: DoStuff[A, B] =
new DoStuff[A, B] { def apply(): Unit = ... body of your ev == null case ...
}
object DoStuff extends DoStuff0 {
implicit def eqDoStuff[A]: DoStuff[A, A] =
new DoStuff[A, A] { def apply(): Unit = ... body of your ev != null case ...
}
class Something[A, B](implicit ds: DoStuff[A, B]) {
...
def doStuff: Unit = ds()
}