When the ternary operator fails

In the specific case where I want the ternary operator to give me an operator, it fails, but the if then else approach works. I expect there is an explanation, or maybe it is a bug.

What does not work

julia> a = "1+2";

julia> op = contains(a, '+') ? + : -
ERROR: syntax: whitespace not allowed after ":" used for quoting
Stacktrace:
 [1] top-level scope
   @ none:1

and what does work

julia> a = "1+2";

julia> if contains(a, '+')
           op = +
       else
           op = -
       end
+ (generic function with 206 methods)

julia> op(4,5)
9

you are running into a disallowed parser state (ending an expression with -
this is an opportunity to use ifelse

a = "1+2"
op = ifelse(contains(a, '+'), +, -)
op == +

or, just enclose the operators in parens

a = "1+2"
op = contains(a, '+') ? (+) : (-)
op === +
2 Likes

Parentheses can also resolve this issue:

julia> op = contains(a, '+') ? (+) : -
+ (generic function with 208 methods)  

I would normally parenthesize both, but apparently the first was enough.