Search code examples
functionjuliascoping

In Julia, why can "if false" statements in local scope modify function definitions?


In Julia 1.4.1, if I define a function in a global scope, modifications after "if false" statements do not affect it, as expected:

test()=0
if false
  test()=1
end

println(test())

This prints "0", as it should. However, when I enclose this code within a local scope, the behavior changes:

function main()
  test()=0
  if false
    test()=1
  end

  println(test())
end

main()

This now prints "1" which I did not expect. If I change "test" to be an array or a float I observe no modification as expected, i.e. the problem does not occur. Why does Julia behave this way for functions?


Solution

  • The solution is to use anonymous functions in cases like this:

    function main()
      test = () -> 0
      if false
        test = () -> 1
      end
    
      println(test())
    end
    
    julia> main()
    0
    

    As for the why, this gets to the core of what it means to define and redefine a particular method of a function.