【问题标题】:Context bound with Infix operator与中缀运算符绑定的上下文
【发布时间】:2016-05-17 08:54:38
【问题描述】:

对于给定的抽象类 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
    }
    }

【问题讨论】:

    标签: scala oop interface


    【解决方案1】:

    如何为 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]]

    【讨论】:

    • 抱歉我的无知,但我不明白如何实现隐式 def numricPoint[T: Numeric]: Point2DInterface[Point2D[T]]。
    • 没关系...我误会了,现在一切都清楚了(:感谢重播!
    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    相关资源
    最近更新 更多