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.

A tuple is just a collection of values — which may be of different types — in between parentheses, as shown.

To assign those values to variable names when calling the function, just use this syntax:

val (stationNumber, stationName) = getRadioStationInfo(...)

When you do this, those two variables will have these values:

stationNumber = 104.3
stationName   = "The Fan"

I wrote more about tuples in the Scala Cookbook, so for more information on this process please see my earlier tutorial, How to define Scala methods that return multiple items.