如何在Scala中组合类型类?

时间:2017-02-27 20:04:13

标签: scala typeclass

我的代码如下:

/**
  * A divisor that operates on real numbers.
  */
case class RealDivisor(divisor: Long)
  extends Divisor[Double, Double]
  with Divisor[Long, Double] // ... with Divisor[Int, Double], etc.
  {

  override def divide(dividend: Double): Double =
    if (divisor != 0) dividend / divisor.toDouble else 0

  def divide(dividend: Long): Double = divide(dividend.toDouble)

}

我更愿意做这样的事情:

case class RealDivisor(divisor: Long) extends Divisor[A: Numeric] {
  // ...
}

因此,我只需要实现一次divide方法。我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

您正在寻找的是field

的想法

Field类型类由例如提供。 Spire