在scala中有参数语法糖

时间:2014-06-20 08:32:47

标签: scala parameters syntactic-sugar

对于依赖于对象的操作,我有一些语法糖:

case class EllipticOperand (p : Point)
{
  def + (q : => Point) = curve.sum(p,q)
  def * (n : => BigInt) = curve.times(p,n)
}
implicit def PointToOperand(p : Point) = EllipticOperand(p)

case class EllipticMultiplier (n : BigInt)
{
def * (p : => Point) = curve.times(p,n)
}
implicit def BigIntToOperand (n : BigInt) = EllipticMultiplier(n)

我想封装在一些class SyntacticSugar[Point](curve : main.Curve[Point])中,以便在其他类定义中使用它,而无需复制/粘贴它。

我试着这样使用它:

val sugar = new util.SyntacticSugar(curve)
import sugar._

但是,这不起作用,我之后无法使用+*

1 个答案:

答案 0 :(得分:4)

如果我按照你建议的方式实施它......

case class Point(x: Int, y: Int)

trait Curve[T] {
  def sum(p: T, q: T): T
  def times(p: T, n: Int): T
}

// dummy implementation
class PointCurve extends Curve[Point] {
  override def sum(p: Point, q: Point) = Point(p.x+q.x, p.y+q.y)
  override def times(p: Point, n: Int) = Point(p.x*n, p.y*n)
}


object util {
  class SyntacticSugar[T](curve: Curve[T]){
    case class EllipticOperand(p: T){
      def +(q: =>T) = curve.sum(p, q)
      def *(n: =>Int) = curve.times(p,n)
    }
    implicit def point2Operand(p: T) = EllipticOperand(p)
  }
}

现在,您可以+使用*Point作为运营商:

scala> val sugar = new util.SyntacticSugar(new PointCurve)
sugar: util.SyntacticSugar[Point] = util$SyntacticSugar@4ed4b486

scala> import sugar._
import sugar._

scala> Point(1,2) + Point(2,3)
res0: Point = Point(3,5)

scala> Point(1,2) * 3
res1: Point = Point(3,6)