Scala Nuggets: The Tasty Tuples

Table of contents
Reading Time: 2 minutes

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
[sourcecode language=”bash”]
scala> val name = ("vikas","hazrati")
name: (java.lang.String, java.lang.String) = (vikas,hazrati)
scala> print(name._1)
vikas
scala> print(name._2)
hazrati
[/sourcecode]

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,

[sourcecode language=”bash”]
scala> val mixed = ("vikas", "hazrati", 36)
mixed: (java.lang.String, java.lang.String, Int) = (vikas,hazrati,36)
scala> print(mixed._3)
36
scala>
[/sourcecode]

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

[sourcecode language=”scala”]
def doSomeHeavyCalculationAndReturnPaymentAndInventoryDetails():(Payment, Inventory )={
val payment = new Payment(12, "leeway")
val inventory = new Inventory(18, 34,"never")
return (payment, inventory)
}
[/sourcecode]

The classes to be returned look like this

[sourcecode language=”scala”]
class Inventory (stock:Int, cost:Long, expiry:String){
}

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

Now, if we execute the method

[sourcecode language=”scala”]
val paymentAndInventoryDetails = doSomeHeavyCalculationAndReturnPaymentAndInventoryDetails()

println(paymentAndInventoryDetails._1)
[/sourcecode]

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
[sourcecode language=”scala”]
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)
}

}
[/sourcecode]
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 …

Written by 

Vikas is the CEO and Co-Founder of Knoldus Inc. 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). Vikas has been working in the cutting edge tech industry for 20+ years. He was an ardent fan of Java with multiple high load enterprise systems to boast of till he met Scala. His current passions include utilizing the power of Scala, Akka and Play to make Reactive and Big Data systems for niche startups and enterprises who would like to change the way software is developed. To know more, send a mail to hello@knoldus.com or visit www.knoldus.com

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading