Search code examples
juliaternary-operator

Does Julia have a ternary conditional operator?


Python, Java and Scala have ternary operators. What is the equivalent in Julia?


Solution

  • For inline use, a ? b : c exists, as mentioned by the previous answer. However it is worth noting that if-else-end in Julia works just like (if cond expr1 expr2) in most Lisp dialects which acts both as the if-clause and as the ternary operator. As such, if-then-else returns the return value of the expression that gets executed.

    Meaning that you can write things like

    function abs(x)
        if x > 0
            x
        else
            -x
        end
    end
    

    and this will return what you want. You do not have to use a return statement to break the function block, you just return the value returned by the if-block.

    Inline, you can write

    if (x > 0) x else -x end 
    

    which will return the same thing as the ternary operator expression (x > 0) ? x : -x , but has the benefit of avoiding perl-ish ?: symbols and is generally more readable, but less chainable.

    Most languages have a ternary operator separate from if-then-else because if clauses are statements, while in lisp-like languages they are expressions just like everything else and have a return value.