Variadic Functions in Crystal

Here’s how you can translate the provided code example to Crystal language in Markdown format suitable for Hugo:


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

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

def sum(*nums : Int32)
  puts nums, " "
  total = 0
  nums.each do |num|
    total += num
  end
  puts total
end

Within the function, the type of nums is equivalent to Array(Int32). We can call nums.size, iterate over it with each, 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 arguments in an array, apply them to a variadic function using the splat (*) operator like this.

nums = [1, 2, 3, 4]
sum(*nums)

To run the program, save the code in a file (e.g., variadic_functions.cr) and use the crystal command to execute it.

$ crystal run variadic_functions.cr
[1, 2] 
3
[1, 2, 3] 
6
[1, 2, 3, 4] 
10

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

Next example: Closures.