Scala Nuggets: The Tasty Tuples

One of the interesting things that Scala has to offer is a concept called Tuples. It is a literal syntax of comma-separated list of items inside parenthesis. Something like (a1, a2, a3). These “groupings” are instantiated as scala.TupleN instances, where the N is the number of items in the tuple. The Scala API defines separate TupleN classes for N between 1 and 22, inclusive. (I am still struggling to find the right answer of why the number is 22 and not 42 or 32, there is some explanation here is you can make sense of it ). Anyway, Tuples can be assigned to variables, passed as values or return them from the methods.

Tuples is a way of pairing discrete pieces of data in some sort of meaningful way.  Ideally, I would mostly use it for the situation where I need to return multiple objects back from a method. If I were to do that in Java, I could have put the objects that I wanted to return in a wrapper class and then return the wrapper object. Workable but probably not as elegant. Further, another uglier way of doing it would be return it as a part of any collection and then have the client logic understand what item contains what. Anyway, with Scala it is easier and cleaner. And the beauty is that there could be different types of objects defined within the tuple.

Let us look at a quick example

scala> val name = ("vikas","hazrati")
name: (java.lang.String, java.lang.String) = (vikas,hazrati)
scala> print(name._1)
scala> print(name._2)

In this example, Scala declares val name as type (String, String). It is actually a Tuple2[String, String] type. As you can see, we could print out the individual pieces together. We could also define a tuple with different items under it. For example,

scala> val mixed = ("vikas", "hazrati", 36)
mixed: (java.lang.String, java.lang.String, Int) = (vikas,hazrati,36)
scala> print(mixed._3)

As you can see we mixed Int and String together. Also, you would notice that the numbering for a Tuple begins from 1 and not 0.
Ok, Let us return it from a method now, assume that there is a method which does some heacy calculations and returns payment and inventory object

def doSomeHeavyCalculationAndReturnPaymentAndInventoryDetails():(Payment, Inventory )={
    val payment = new Payment(12, "leeway")
    val inventory = new Inventory(18, 34,"never")
    return (payment, inventory)

The classes to be returned look like this

class Inventory (stock:Int, cost:Long, expiry:String){

class Payment(amount:Int, description:String){
  override def toString = "Amount is " + amount+ " and description is " + description

Now, if we execute the method

  val paymentAndInventoryDetails = doSomeHeavyCalculationAndReturnPaymentAndInventoryDetails()


The ouput would be “Amount is 12 and description is leeway” because we have overridden the toString function for Payment.

Tuples can also be used to examine key-value pairs from a map as a single, composite entity.

For example

def readAMap() = {

    val score = Map("India" -> 1, "Pakistan" -> 3, "SriLanka" -> 2, "NewZealand" -> 4)

    score.foreach {
      tuple: (String, Int) =>
        val (country, value) = tuple

        println("    " + country + " : " + value)


when this method is called it would result in the following output

India : 1
Pakistan : 3
SriLanka : 2
NewZealand : 4

Keep tuned for more nuggets coming your way …

About Vikas Hazrati

Vikas is the Founding Partner @ Knoldus which is a group of software industry veterans who have joined hands to add value to the art of software development. Knoldus does niche Reactive and Big Data product development on Scala, Spark and Functional Java. Knoldus has a strong focus on software craftsmanship which ensures high-quality software development. It partners with the best in the industry like Lightbend (Scala Ecosystem), Databricks (Spark Ecosystem), Confluent (Kafka) and Datastax (Cassandra). To know more, send a mail to or visit
This entry was posted in Java, Scala and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s