【发布时间】: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
}
}
【问题讨论】: