Skip to content

Functions and Methods

Closures

Captured variables are pointers to the same variables in the enclosing scope. If the values of the captured variables change on the outside, they also change inside the closure:

c1 = 5;
function g(x)
  let c2 = c1; # does not do anything, but may improve performance
  return x + c2
end
g(5) == 10;
c2 = 20;
g(5) == 25;

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, ).