Function not defined when occurring in else-clause inside of another function

Hi there,

I ran into some weird behavior that I don’t understand. When having two possible function declarations inside an if-else-statement which is wrapped in some outer function, the assignment inside the else-clause doesn’t work. ("Yah, I know that’s bad programming style and I changed my code. However, I would really like to understand what’s going wrong here :wink:)

Here is a minimum working example:

function test(flag=true)
    if flag
        myfunc() = 1
    else
        myfunc() = 0
    end
        println(myfunc())
    return
end

Running this function as test() or test(flag=true) works perfectly fine and prints me a 1. However, when calling it as test(flag=false) the code crashes with ERROR: UndefVarError: myfunc not defined.

Why is this happening?

Thank you very much
G

See JuliaLang/julia#15602. You need to use anonymous functions:

function test(flag=true)
    if flag
        myfunc = () -> 1
    else
        myfunc = () -> 0
    end
    println(myfunc())
    return
end
2 Likes

thank you