Scala:隐式转换器&中缀符号&运算符优先级

时间:2014-01-31 14:32:01

标签: scala dsl infix-notation

如果您发现提供的代码超出了问题的范围,请原谅。在代码底部s1 (500.m + 10.km) toKm表达式成功编译,但它看起来并不自然。无论如何我们可以实现这种语法(500 m + 10 km) toKm

object Main extends App {
  sealed trait Measure {
    def toM: M = this match {
      case Km(km) => M(km * 1000)
      case m: M   => m
    }

    def toKm: Km = this match {
      case M(m)   => Km(m / 1000)
      case km: Km => km
    }
  }
  case class Km(val m: Double) extends Measure {
    def +(that: Any): Km = {
      that match {
        case Km(rhs) => Km(m + rhs)
        case M(rhs)  => Km(m + rhs / 1000)
      }
    }
    override def toString() = m + " km"
  }

  case class M(val m: Double) extends Measure {
    def +(that: Any): M = {
      that match {
        case Km(rhs) => M(m + rhs * 1000)
        case M(rhs)  => M(m + rhs)
      }
    }

    override def toString() = m + " m"
  }

  implicit class MeasureConverter(val measure: Double) extends AnyVal {
    def km = new Km(measure)
    def m = new M(measure)
  }

  val s1 = (500.m + 10.km) toKm

  val s2 = (500 m + 10 km) toKm

}

1 个答案:

答案 0 :(得分:1)

由于Scala的语法规则,您需要将它们括在括号中。

((500 m) + (10 km)) toKm

对于代码样式的一致性和other reasons,我建议不要在符号运算符(本例中为+)之外使用中缀表示法,即:

(500.m + 10.km).toKm