【问题标题】:Idiomatic way of branching depending on the existance of a type evidence in Scala根据 Scala 中类型证据的存在的惯用分支方式
【发布时间】:2014-07-01 21:31:31
【问题描述】:

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

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

【问题讨论】:

  • 为什么不直接对待它,就像对待null 的可能性在其他任何地方(即Option(ev))一样?

标签: scala types implicits


【解决方案1】:

只需使用类型类,

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

【讨论】:

  • 如果此代码 > 更改为 >
  • @Cloudtech 它取决于上下文,但是如果像这里一样,实例可以在实例化Something 时一劳永逸地修复,那么为什么要推迟它并可能支付每次调用它的成本调用该方法的时间?
猜你喜欢
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 2016-10-12
  • 2017-01-27
  • 1970-01-01
  • 2015-02-07
  • 1970-01-01
  • 2011-06-16
相关资源
最近更新 更多