Scala Nuggets: The Tasty Tuples

Posted on Wednesday, March 30, 2011

0


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)
vikas
scala> print(name._2)
hazrati

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)
36
scala>

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()

    println(paymentAndInventoryDetails._1)

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 …

Advertisements
Tagged: ,
Posted in: Java