Why is this function valid julia syntax?

The following function is valid julia code (in the sense that there is no parsing error)

function temp(x::AbstractArray)
    x[1] = 1 +
 return nothing
# This is the same as writing x[1] = 1 + return nothing
end

which lowers to

CodeInfo(
1 ─     return Main.nothing
)

I find this very unintuitive and would have expected the code to error instead of lowering to the above expression. Why is 1 + return nothing valid julia syntax, and why is the assignment statement in this case essentially ignored?

I guess because:

  1. return ... is a valid Julia expression, i.e. it can be combined with other expressions. This is very convenient e.g. in REPL.
  2. Assignment happens after the return and thus is effectively unreachable.
7 Likes