繁体   English   中英

上下文与Infix运算符绑定

[英]Context bound with Infix operator

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

abstract class Edge2D[T : Point2DInterface] {

  val p1: T
  val p2: T

  def length(): Double = {
    implicitly[Point2DInterface[T]].Sub(p1, p2)
  }
}

trait Point2DInterface[T] {
  def Sub(first: T, second: T): Double
}

通过以下实现,当T = DoublePoint2D时

object Implicits {

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

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

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

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

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

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

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

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

使它成为泛型,即用Point2D[T: Numeric]替换IntPoint2DDoublePoint2D Point2D[T: Numeric]和隐implicit def numericPoint2D[T: Numeric]: Point2DInterface[Point2D[T]]的两个隐式对象implicit def numericPoint2D[T: Numeric]: Point2DInterface[Point2D[T]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM