I implemented a ternary operator like Java's <condition> ? <if true> : <if false>
, substituting /
for :
, since :
is not a valid identifier:
case class Ternary[T](val o: Option[T]) {
def / (f: => T) = o getOrElse f
}
implicit def boolToTernary(cond: Boolean) = new {
def ? [T](f: => T) = if(cond) Ternary(Some(f))
else Ternary[T](None)
}
It works fine in general, e.g.
scala> (1 > 2) ? "hi" / "abc"
res9: java.lang.String = abc
but falls down in the following case:
scala> (1 > 2) ? 5 / 6.0
<console>:33: error: type mismatch;
found : Double(6.0)
required: Int
(1 > 2) ? 5 / 6.0
^
Is there any tweaking I can do to the types in order to get this to work like the built-in if (1 > 2) 5 else 6.0
does? I googled for similar solutions and the implementations I found all exhibited the same behaviour.