Optional and keyword arguments

When defining functions, one or more arguments can be given a default value such as f(arg = val). If no parameter is supplied for arg, then val is taken as the value of arg. The position of these arguments in the function's input is important, just as it is for normal arguments; that's why they are called optional positional arguments. Here is an example of an f function with an optional argument b:

# code in arguments.jl: 
f(a, b = 5) = a + b

For example, if it's f(1), then it returns 6; f(2, 5) returns 7; and f(3) returns 8. However, calling it with f() or f(1,2,3) returns an error, because there is no matching function f with zero or three arguments. These arguments are still only defined by position: calling f(2, b = 5) raises an error as ERROR: function f does not accept keyword arguments.

Until now, arguments were only defined by position. For code clarity, it can be useful to explicitly call the by name, so they are called optional keyword arguments. Because the arguments are given explicit names, their order is irrelevant, but they must come last and be separated from the positional arguments by a semi-colon (;) in the argument list, as shown in this example:

 k(x; a1 = 1, a2 = 2) = x * (a1 + a2) 

Now, k(3, a2 = 3) returns 12, k(3, a2 = 3, a1 = 0) returns 9 (so their position doesn't matter), but k(3) returns 9 (demonstrating that the keyword arguments are optional). Normal, optional positional, and keyword arguments can be combined as follows:

function allargs(normal_arg, optional_positional_arg=2; keyword_arg="ABC") 
    print("normal arg: $normal_arg" - ) 
    print("optional arg: $optional_positional_arg" - ) 
    print("keyword arg: $keyword_arg") 
end 

If we call allargs(1, 3, keyword_arg=4), it prints normal arg: 1 - optional arg: 3 - keyword arg: 4.

A useful case is when the keyword arguments are splatted as follows:

function varargs2(;args...) 
    args 
end 

Calling this with varargs2(k1="name1", k2="name2", k3=7) returns pairs(::NamedTuple) with three entries: (:k1,"name1") (:k2,"name2") (:k3,7). Now, args is a collection of (key, value) tuples, where each key comes from the name of the keyword argument, and it is also a symbol (refer to the Strings section of Chapter 2, Variables, Types, and Operations) because of the colon (:) as prefix.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset