Reputation: 1597
Please excuse me if you find the supplied code beyond the scope of the question. At the bottom of the code s1 (500.m + 10.km) toKm
expression compiles successfully but the it does not look natural. Is there anyway we can achieve this syntax (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
}
Upvotes: 0
Views: 396
Reputation: 43309
Due to Scala's syntactic rules you'll need to enclose those in brackets.
((500 m) + (10 km)) toKm
For code style consistency and other reasons I would however advise against ever using infix notation for anything other than symbolic operators (+
in this case), i.e.:
(500.m + 10.km).toKm
Upvotes: 1