A Java tuple class (Tuple2 or Pair, if you prefer) alvin January 25, 2017 - 2:41pm

After working with Scala for a long time, I had to come back to Java for a while to work on an Android app. Right away I missed a lot of things from the Scala world, including all of the built-in Scala collection methods, and other things as simple as the Scala Tuple classes.

If you haven’t used them before, a Scala Tuple class lets you write code like this:

Tuple<String, Integer> t = new Tuple<>("age", 41);

If you’re comfortable with generics, the Java implementation of a Tuple class like this is simple:

How to write a Scala function that returns multiple values alvin July 21, 2016 - 3:29pm

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) alvin June 13, 2015 - 7:49pm

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).”


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


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 alvin August 4, 2013 - 11:52am

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: