Variadic Functions in Julia

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

Here’s a function that will take an arbitrary number of ints as arguments.

function sum(nums...)
    println(nums, " ")
    total = 0
    for num in nums
        total += num
    end
    println(total)
end

Within the function, the type of nums is equivalent to Vector{Int}. We can call length(nums), iterate over it with a for loop, etc.

Variadic functions can be called in the usual way with individual arguments.

sum(1, 2)
sum(1, 2, 3)

If you already have multiple args in a vector, apply them to a variadic function using ... like this.

nums = [1, 2, 3, 4]
sum(nums...)
$ julia variadic_functions.jl
[1, 2] 
3
[1, 2, 3] 
6
[1, 2, 3, 4] 
10

Another key aspect of functions in Julia is their ability to form closures, which we’ll look at next.