Multiple Return Values in Scala

Scala has built-in support for multiple return values through tuples. This feature is used often in idiomatic Scala, for example to return both result and error values from a function.

import scala.io.StdIn.readLine

// The (Int, Int) in this function signature shows that
// the function returns a tuple of 2 Ints.
def vals(): (Int, Int) = {
  (3, 7)
}

@main def main() = {
  // Here we use the 2 different return values from the
  // call with pattern matching.
  val (a, b) = vals()
  println(a)
  println(b)

  // If you only want a subset of the returned values,
  // you can use the underscore '_' as a wildcard.
  val (_, c) = vals()
  println(c)
}

When you run this program, you’ll see:

$ scala multiple_return_values.scala
3
7
7

In Scala, we use tuples to return multiple values from a function. The function vals() returns a tuple (Int, Int), which is then deconstructed in the main function using pattern matching.

The underscore _ in Scala serves a similar purpose to Go’s blank identifier, allowing you to ignore certain values when destructuring tuples or in other pattern matching scenarios.

Accepting a variable number of arguments is another nice feature of Scala functions; we’ll look at this in a future example.