How to use `kwargs` to avoid passing around keyword arguments?

If you are only passing the arguments around to the inner function, you can use something like this:

julia> _f(x; a = 1, b = 2) = x + a + b  # inner function, define all parameters explicitly
_f (generic function with 1 method)

julia> f(x; kargs...) = _f(x; kargs...)  # only pass the kargs... over
f (generic function with 1 method)

julia> f(1)
4

julia> f(1; a = 2)
5

With that you can add keyword parameters to your inner function without having to modify the outer interface.

The other alternative, which is also common, is to define a structure with all parameters and pass that instead, like:

julia> Base.@kwdef struct Options
           a::Int = 1
           b::Int = 2
       end
Options

julia> _f(x; opt = Options()) = x + opt.a + opt.b
_f (generic function with 1 method)

julia> f(x; opt=Options()) = _f(x; opt=opt)
f (generic function with 1 method)

julia> f(1)
4

julia> f(1; opt = Options(a=2))
5

In some situations this provides a more explicit and clearly maintainable code, I think.

7 Likes