Consider a simple Collection, searching the min and max in one iteration:
val v = Vector (2, 1, 3, 5, 4)
val mima = (v(0), v(0))
val mami = (mima /: v) {case ((a, b), c) => if (c<a) (c, b) else if (c>b) (a, c) else (a, b)}
So far, so straight forward. If I replace the if/else with the ternary operator (X ? Y : Z), it doesn't work; I get an error:
val mami = (mima /: v) {case ((a, b), c) => (c<a) ? (c, b) : (c>b) ? (a, c) : (a, b)}
<console>:1: ';' expected but : found.
at the last colon. Adding parens didn't help:
val mami = (mima /: v) {case ((a, b), c) => (c<a) ? (c, b) : ((c>b) ? (a, c) : (a, b))}
Do I make a silly mistake or is there is a subtle problem with the nested ternary operator?
Hunting this problem down, it isn't related to folds, only:
if (c < 4) "small" else if (c > 8) "big" else "medium"
works
(c < 4) ? "small" : (c > 8) ? "big" : "medium"
fails the same way.
Scala doesn't have a ternary operator, because it has
ifwhich works as expression, so you can do things like:You can also use it in fold: