Skip to content

Functions and Methods

Default arguments

Given a function that accepts keyword arguments:

function foo1(x; a = 1, b = 2, c = 3, d = 4)
    @show a, b, c, d
end

Setting default arguments can be done with a NamedTuple:

default_args = (:b => 22, :d => 44);
foo1(1; default_args..., b = 33)
# Result: (a, b, c, d) = (1, 22, 3, 44)
# But this loses the non-default value of `b`:
foo1(1; b = 33, default_args...)

One can set default arguments inside the function as a NamedTuple and merge:

function foo(; kwargs...)
   # Note that `x = 17` works as well as `:x => 17`
   defaults = (x = 17, );
   args = merge(defaults, kwargs);
   println(args[:x])
   # Or call another function `bar(; args...)`
end

The next obvious step would be to define foo_defaults() = (x = 17, ).