上下文与Infix运算符绑定

时间:2016-05-17 08:54:39

标签: scala oop interface

对于给定的抽象类Edge2D,我采用的是泛型类型T. 将上下文绑定到某个接口Point2DInterface。

object Implicits {

  implicit object DoublePoint2DInterface extends Point2DInterface[DoublePoint2D] {
    def Sub(first: DoublePoint2D, second: DoublePoint2D): Double = {
      first - second
    }
  }
}

使用以下实现时,T = DoublePoint2D

  def length(): Double = {
    p1 - p2
  }

如何为T创建中缀运算符?所以我可以写

object Implicits {

  implicit object DoublePoint2DInterface extends Point2DInterface[DoublePoint2D] {
    def Sub(first: DoublePoint2D, second: DoublePoint2D): Double = {
      first - second
    }
  }

implicit object IntPoint2DInterface extends Point2DInterface[IntPoint2D] {
    def Sub(first: IntPoint2D, second: IntPoint2D): Double = {
      first - second
    }
    }

不管上一个问题,我想知道,有没有办法结合起来 隐式对象的实现? 例如,组合DoublePoint2DInterface和IntPoint2DInterface。

document.getElementById("dtBody1")

1 个答案:

答案 0 :(得分:0)

  

如何为T创建中缀运算符?

implicit class Point2DInterfaceOps[T](x: T)(implicit evidence: Point2DInterfaceOps[T]) {
  def -(y: T) = evidence.Sub(x, y)
  ...
}
  

不管上一个问题,我想知道,有没有办法组合隐式对象的实现?

将其设为通用,即将IntPoint2DDoublePoint2D替换为Point2D[T: Numeric],将两个隐含对象替换为implicit def numericPoint2D[T: Numeric]: Point2DInterface[Point2D[T]]