daycaster
daycaster

Reputation: 2707

Keyword argument aliases

What's a good way to allow aliases for keyword arguments. Say I want an interface like this:

function f(a, b; k1=1, k2=2)
    println(a, b)
    println(k1, k2)
end

function f(a, b; key1=1, key2=2)
    println(a, b)
    println(key1, key2)
end

function f(a, b; kw1=1, kw2=2)
    println(a, b)
    println(kw1, kw2)
end

function f(a, b; keyword1=1, keyword2=2)
    println(a, b)
    println(keyword1, keyword2)
end

so you could call f(1, 2, kw1=3, kw2=4) or f(1, 2, keyword1=3, keyword2=4) and run the same function.

Upvotes: 1

Views: 146

Answers (1)

mbauman
mbauman

Reputation: 31372

I would really recommend avoiding this, but you can "cascade" keywords together, from left to right in their definition order:

julia> function f(a, b; k1=1, k2=2, key1=k1, key2=k2, keyword1=key1, keyword2=key2)
           println(a, b)
           println(keyword1, keyword2)
       end
f (generic function with 1 method)

julia> f(1,2,k1=3,k2=4)
12
34

julia> f(1,2,key1=3,k2=4)
12
34

julia> f(1,2,key1=3,keyword2=4)
12
34

Note that you set the precedence order in the definition:

julia> f(1,2,key1=3,k1=4)
12
32

Upvotes: 5

Related Questions