Strange behaviour with if-else-Statements

This is not a bug. Starting a line with + doesn’t connect it with the previous line.

julia> 5
5

julia> +5
5

julia> 5 + 5
10

This is what’s happening

julia> if true
           10
       end + 5
15

julia> if false
           10
       end + 5
ERROR: MethodError: no method matching +(::Nothing, ::Int64)

You’re hitting the else case (i.e. your condition is false) which returns nothing. Nothing + Int is an error. The reason putting +5 on a new line works is because it’s parsed as

nothing # this line does nothing
+5 # +5 === 5, coincidentally this is what you wanted, but not for the right reason

You can use ternary expressions for compact if statements

x = 1 == 2 ? 15 : 10

Or you can use the boolean to do something directly if that makes sense in context

x = 10 + 5 * (1 == 2)
8 Likes