home search about rss feed twitter ko-fi

Functions: varargs Parameters (Scala 3 Video)

When creating a function, you can declare that a function parameter can be repeated. We call this a varargs parameter. There are two rules for varargs parameters:

  • Can only have one varargs parameters per input group
  • It must be the last parameter

Define a varargs parameter by adding a * symbol after the input parameter type.

Examples

// [1] define a function with a varargs parameter
def addAll(ints: Int*): Int = 
    ints.sum

// [2] you can call the function in all these different ways
addAll()
addAll(1)
addAll(1, 2, 3)

Other examples

This function takes a variable number of String parameters:

// varargs
@main def hello(names: String*): Unit =
    names.foreach(name => println(s"Hello, $name"))

This one won’t compile because I attempt to use it before another parameter; this violates the rules:

def printAll(strings: String*, i: Int): Unit = 
    strings.foreach(println)

Advanced: Use _* to adapt a sequence

I didn’t show it in the video, but when you want to pass a sequence into a function that has a varargs parameter, you need to adapt the sequence using the special _* characters:

// a varargs function:
def addAll(ints: Int*): Int = 
    ints.sum

// attempt to pass a List into the function:
val xs = List(1, 2, 3)
addAll(xs)    // fails

// solution: convert the List; this works:
addAll(xs: _*)

I like to think of _* as being like the “splat” character (*) in UNIX and Linux systems.

Update: All of my new videos are now on
LearnScala.dev