习得的分支方式取决于Scala中类型证据的存在

时间:2014-07-01 21:31:32

标签: scala types implicits

我发现自己不止一次写下以下丑陋的模式:

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]之类的异端。

1 个答案:

答案 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()
}