[英]Context bound with Infix operator
For the given abstract class Edge2D I am taking a generic type T with context bound to some interface Point2DInterface. 对于给定的抽象类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
}
With the following implementation, when T=DoublePoint2D 通过以下实现,当T = DoublePoint2D时
object Implicits {
implicit object DoublePoint2DInterface extends Point2DInterface[DoublePoint2D] {
def Sub(first: DoublePoint2D, second: DoublePoint2D): Double = {
first - second
}
}
}
How can I create an infix operator for T? 如何为T创建中缀运算符? so I could write 所以我可以写
def length(): Double = {
p1 - p2
}
Regardless to the previous question, I wonder, is there a way to combine the implementations of the implicit objects? 不管上一个问题,我想知道,有没有办法结合隐式对象的实现? For example, combining DoublePoint2DInterface and IntPoint2DInterface. 例如,组合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
}
}
How can I create an infix operator for T? 如何为T创建中缀运算符?
implicit class Point2DInterfaceOps[T](x: T)(implicit evidence: Point2DInterfaceOps[T]) {
def -(y: T) = evidence.Sub(x, y)
...
}
Regardless to the previous question, I wonder, is there a way to combine the implementations of the implicit objects? 不管上一个问题,我想知道,有没有办法结合隐式对象的实现?
Make it generic, ie replace IntPoint2D
and DoublePoint2D
with Point2D[T: Numeric]
and the two implicit objects with implicit def numericPoint2D[T: Numeric]: Point2DInterface[Point2D[T]]
使它成为泛型,即用Point2D[T: Numeric]
替换IntPoint2D
和DoublePoint2D
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.