[英]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]
替換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.