🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Vararg Types

Vararg types are argument types that accept a varying number of values. The rest arguments arrive together for the function body to use.

One function sums any number of values

The rest argument gathers every value. The same function works for three values and for two values.

addall(xs::Vararg{Number}) = sum(xs)
println(addall(1, 2, 3))
println(addall(1.5, 2.5))

A fixed count accepts exactly two values

The count in the type fixes the number of values. The two values combine into one result.

pair(xs::Vararg{Int, 2}) = xs[1] * 10 + xs[2]
println(pair(4, 5))

Rest arguments support indexing

The first and last rest values are reached by position. Their sum is the result.

firstlast(xs::Vararg{Number}) = xs[1] + xs[end]
println(firstlast(10, 20, 30))

Example

report(xs::Vararg{Number}) = begin
println(length(xs))
println(sum(xs))
println(xs[1])
println(xs[end])
end
report(5, 10, 15, 20)

Key points

  • Vararg{Number}: a rest argument type that accepts any number of numbers.
  • Rest argument: the trailing argument that gathers the extra values.
  • Vararg{Int, 2}: a rest argument type that fixes the count at exactly two integers.
  • Use Vararg to write one function for one value, three values, or ten values.
  • Length: the length of the rest arguments tells how many values arrived.

In this example, report takes four rest values. It prints the count, the sum, the first value, and the last value in that order.

Note

a Vararg argument is checked like any other argument type, so a wrong value is refused.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

How many integers does Vararg{Int, 2} accept?