# Conditional function definition

**URL:** <https://discourse.julialang.org/t/conditional-function-definition/27348>\
**Category:** General Usage\
**Created:** [August 9, 2019, 10:19am UTC](https://discourse.julialang.org/t/conditional-function-definition/27348 "2019-08-09T10:19:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![antoine-levitt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/antoine-levitt/32/4008_2.png) [@antoine-levitt](https://discourse.julialang.org/u/antoine-levitt)\
**Post date:** [August 9, 2019, 10:19am UTC](https://discourse.julialang.org/t/conditional-function-definition/27348/1 "2019-08-09T10:19:36Z")

</div>

What is going on here?

```julia
function g1(a)
    if a == 0
        f(x) = 2
    else
        f(x) = 3
    end
    println(f(1))
end

function g2(a)
    f = x -> 1
    if a == 0
        f(x) = 2
    else
        f(x) = 3
    end
    println(f(1))
end
function g3(a)
    f(x) = 1
    if a == 0
        f(x) = 2
    else
        f(x) = 3
    end
    println(f(1))
end
function g4(a)
    f = x -> 1
    if a == 0
        f = x -> 2
    else
        f = x -> 3
    end
    println(f(1))
end

g1(0) # 3
g2(0) # 3
g3(0) # 3
g4(0) # 2
# g1(1) #fails
g2(1) #1
g3(1) #3
g4(1) #1

```

My takeaway is that only the 4th version does what I want, but I’m very confused by the other cases. Also this is reduced from a case where I got a warning about function redefinition, but that doesn’t seem to happen in this case…

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [August 9, 2019, 3:58pm UTC](https://discourse.julialang.org/t/conditional-function-definition/27348/2 "2019-08-09T15:58:45Z")

</div>

See [disallow methods of local functions in different blocks · Issue #15602 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/15602)

---

<div class="post-metadata">

**Author:** ![antoine-levitt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/antoine-levitt/32/4008_2.png) [@antoine-levitt](https://discourse.julialang.org/u/antoine-levitt)\
**Post date:** [August 9, 2019, 7:07pm UTC](https://discourse.julialang.org/t/conditional-function-definition/27348/3 "2019-08-09T19:07:42Z")

</div>

Thanks! That’s one nasty bug.
