# Defining a conditional method in Julia

**URL:** <https://discourse.julialang.org/t/defining-a-conditional-method-in-julia/23193>\
**Category:** New to Julia\
**Created:** [April 16, 2019, 8:44am UTC](https://discourse.julialang.org/t/defining-a-conditional-method-in-julia/23193 "2019-04-16T08:44:46Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ahmetumutdurmus](https://avatars.discourse-cdn.com/v4/letter/a/ed655f/32.png) [@ahmetumutdurmus](https://discourse.julialang.org/u/ahmetumutdurmus)\
**Post date:** [April 16, 2019, 8:44am UTC](https://discourse.julialang.org/t/defining-a-conditional-method-in-julia/23193/1 "2019-04-16T08:44:46Z")

</div>

Hello,

We can define methods on functions that depend on types of arguments. But can we define methods that depend on some conditionals of arguments. To make myself clear the following syntax is not permitted:

```julia
function foo(x::dims(x)==2)
    println("2")
end

function foo(x::dims(x)==3)
    println("3")
end

```

We could circumvent this problem by say:

```julia
function foo(x)
    if dims(x) == 2
        foo2(x)
    elseif dims(x) == 3
        foo3(x)
    end
end

foo2(x) = println("2") 
foo3(x) = println("3")

```

Is there any other way (a more concise or elegant way) of dealing with this?

Thanks.

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [April 16, 2019, 8:48am UTC](https://discourse.julialang.org/t/defining-a-conditional-method-in-julia/23193/2 "2019-04-16T08:48:42Z")

</div>

You can use traits, or more generally convert the information that you condition on to a type. Eg

```julia
_dims(x) = Val{dims(x)}()
foo(x) = _foo(_dims(x), x)
_foo(::Val{2}, x) = println("2")
_foo(::Val{3}, x) = println("3")

```

This involves dynamic dispatch (except when the compiler gets clever and manages to fold the constants), so it will not help you make things faster. But it can provide an extensible alternative to a bunch of `if`s.

---

<div class="post-metadata">

**Author:** ![ahmetumutdurmus](https://avatars.discourse-cdn.com/v4/letter/a/ed655f/32.png) [@ahmetumutdurmus](https://discourse.julialang.org/u/ahmetumutdurmus)\
**Post date:** [April 16, 2019, 9:01am UTC](https://discourse.julialang.org/t/defining-a-conditional-method-in-julia/23193/3 "2019-04-16T09:01:32Z")

</div>

Thanks for your help!
