tuple3

How to write a Scala function that returns multiple values

As a quick note today, if you want to write a Scala function that returns multiple values, just return the values inside a tuple. For example, I just wrote a function to return radio station number and name, and the last part of that function looks like this:

def getRadioStationInfo(...) = {
   ...
   (104.3, "The Fan")
}

The two values are returned in an instance of a Scala Tuple2 class.

How to define Scala methods that return multiple items (tuples)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 5.5, “How to define Scala methods that returns multiple items (tuples).”

Problem

You want to return multiple values from a method, but don’t want to wrap those values in a makeshift class.

Solution

Although you can return objects from methods just as in other OOP languages, Scala also lets you return multiple values from a method using tuples. First, define a method that returns a tuple:

Scala tuple examples and syntax

Scala FAQ: Can you share some examples of using tuples in Scala?

A Scala tuple is a class that can contain a miscellaneous collection of elements. I like to think of them as a little bag or container you can use to hold things and pass them around.

You create a tuple with the following syntax, enclosing its elements in parentheses. Here's a tuple that contains an Int and a String: