Easy Tutorial
❮ Scala Extractors Scala Tutorial ❯

Scala Tuples

Scala Collections

Like lists, tuples are immutable, but unlike lists, tuples can contain elements of different types.

The values of a tuple are composed by enclosing individual values in parentheses. For example:

val t = (1, 3.14, "Fred")

The above example defines three elements in the tuple, with corresponding types of [Int, Double, java.lang.String].

Additionally, we can define it in the following way:

val t = new Tuple3(1, 3.14, "Fred")

The actual type of a tuple depends on the types of its elements. For example, (99, "tutorialpro") is Tuple2[Int, String], and ('u', 'r', "the", 1, 4, "me") is Tuple6[Char, Char, String, Int, Int, String].

Currently, Scala supports tuples up to a maximum length of 22. For larger lengths, you can use collections or extended tuples.

Accessing elements of a tuple can be done through numerical indexing, as in the following tuple:

val t = (4,3,2,1)

We can access the first element with t._1, the second element with t._2, as shown below:

Example

object Test {
   def main(args: Array[String]) {
      val t = (4,3,2,1)

      val sum = t._1 + t._2 + t._3 + t._4

      println( "The sum of the elements is: " + sum )
   }
}

Executing the above code will output:

$ scalac Test.scala 
$ scala Test
The sum of the elements is: 10

Iterating Over Tuples

You can iterate over all elements of a tuple using the Tuple.productIterator() method:

Example

object Test {
   def main(args: Array[String]) {
      val t = (4,3,2,1)
      
      t.productIterator.foreach{ i => println("Value = " + i) }
   }
}

Executing the above code will output:

$ scalac Test.scala 
$ scala Test
Value = 4
Value = 3
Value = 2
Value = 1

Converting Tuples to Strings

You can use the Tuple.toString() method to combine all elements of a tuple into a single string, as shown in the following example:

Example

object Test {
   def main(args: Array[String]) {
      val t = new Tuple3(1, "hello", Console)
      
      println("The concatenated string is: " + t.toString() )
   }
}

Executing the above code will output:

$ scalac Test.scala 
$ scala Test
The concatenated string is: (1,hello,scala.Console$@4dd8dc3)

Swapping Elements

You can use the Tuple.swap method to swap the elements of a tuple. Here is an example:

Example

object Test {
   def main(args: Array[String]) {
      val t = new Tuple2("www.google.com", "www.tutorialpro.org")
      
      println("The tuple after swapping: " + t.swap )
   }
}

Executing the above code will output:

$ scalac Test.scala 
$ scala Test
The tuple after swapping: (www.tutorialpro.org,www.google.com)

Scala Collections

❮ Scala Extractors Scala Tutorial ❯