Julia Varargs & Keyword Arguments
Besides ordinary positional arguments, Julia functions can accept a variable number of arguments (varargs) and keyword arguments that are passed by name. Together they make flexible, readable APIs.
Varargs with ...
Put ... after the last parameter to collect any remaining arguments into a tuple:
function total(xs...)
println("got ", length(xs), " argument(s): ", xs)
return sum(xs; init=0)
end
println(total())
println(total(5))
println(total(1, 2, 3, 4))
describe(name, tags...) = "$name [" * join(tags, ", ") * "]"
println(describe("photo.jpg", "beach", "summer", "2024"))got 0 argument(s): ()
0
got 1 argument(s): (5,)
5
got 4 argument(s): (1, 2, 3, 4)
10
photo.jpg [beach, summer, 2024]
Splatting
The same ... used in a call does the opposite: it splats a collection into separate arguments.
point = (3, 4)
println(hypot(point...)) # same as hypot(3, 4)
nums = [8, 2, 5]
println(max(nums...))
println(string(nums...))
args = ("a", "b", "c")
println(join([args...], "-"))
println([nums..., 10, 11]) # splat inside an array literal5.0
8
825
a-b-c
[8, 2, 5, 10, 11]
Tip: Splatting a very long array into a function call (thousands of elements) is slow. Prefer functions that take a collection, such as
maximum(nums)instead ofmax(nums...).
Keyword arguments
Parameters after a semicolon in the signature are keyword arguments. Callers pass them by name, in any order, and they usually have defaults:
function make_label(text; size=12, bold=false, color="black")
style = bold ? "bold " : ""
return "$(style)$(size)pt $color: $text"
end
println(make_label("Title"))
println(make_label("Title", bold=true))
println(make_label("Note"; color="gray", size=9))12pt black: Title
bold 12pt black: Title
9pt gray: Note
In the call, the semicolon is optional: f(x, size=9) and f(x; size=9) mean the same thing.
Required keyword arguments
A keyword without a default is required. Omitting it raises an error:
connect(; host, port=5432) = "connecting to $host:$port"
println(connect(host="db.local"))
try
connect()
catch e
println(sprint(showerror, e))
endconnecting to db.local:5432
UndefKeywordError: keyword argument `host` not assigned
Passing keywords along
kwargs... collects any extra keyword arguments. They arrive as a collection of name => value pairs that you can inspect or pass on to another function:
function report(title; kwargs...)
println(title)
for (key, value) in kwargs
println(" ", key, " = ", value)
end
end
report("Settings", theme="dark", fontsize=14)
base_label(text; size=10, bold=false) = "$text ($(size)pt, bold=$bold)"
wrapper(text; kw...) = "[" * base_label(text; kw...) * "]"
println(wrapper("hi", bold=true))
opts = (size=20, bold=true)
println(base_label("big"; opts...))Settings
theme = dark
fontsize = 14
[hi (10pt, bold=true)]
big (20pt, bold=true)
wrapper forwards whatever keywords it received to base_label. In the last call, splatting a NamedTuple after ; passes its fields as keyword arguments, so base_label receives size=20 and bold=true.
Combining everything
The order in a signature is: required positional, optional positional, varargs, then ; and keyword arguments.
function plot_line(xs, ys=xs; title="untitled", style...)
n = length(xs)
extras = isempty(style) ? "" : " with " * join(["$k=$v" for (k, v) in style], ", ")
return "$title: $n points$extras"
end
println(plot_line(1:5))
println(plot_line(1:3, [2, 4, 6]; title="doubling", color="red", width=2))untitled: 5 points
doubling: 3 points with color=red, width=2
Test yourself
Inside f(xs...) = ..., what type of collection is xs?
- A Vector
- A Tuple
- A Dict
- A Set
Which signature declares scale as a keyword argument?
- f(x, scale=1)
- f(x; scale=1)
- f(x, :scale=1)
- f(x)(scale=1)
What does max([4, 9, 1]...) do?
- Returns [9]
- Splats the array into max(4, 9, 1) and returns 9
- Throws an error
- Returns the array