All ways to define functions in Julia?

The last definition of f is used. Some may see this as a bug. To avoid this “behaviour” use anonymous functions instead.

julia> function fn_generator()
           if true
               f = () -> 0
           else
               f = (x, y) -> x+y
           end
       end
fn_generator (generic function with 1 method)

julia> name = fn_generator()
#10 (generic function with 1 method)

julia> name()
0

See disallow methods of local functions in different blocks · Issue #15602 · JuliaLang/julia · GitHub and Defining a function inside if...else..end NOT as expected?.

5 Likes