Tuples

Let us see tuples in detail

  • A tuple is another data structure in Scala
  • It can hold heterogeneous elements
  • Syntax for tuple val t = (1, "Hello World")
  • Another syntax for tuple val t: (Int, String) = (1, "Hello World")
  • Tuple has a handful of methods
  • Elements of tuples can be accessed using _ notation (t._1 will return 1 and t._2 return Hello World)
  • If there are 2 elements it is called also known as pair
  • Elements of a tuple can be collections and vice versa
  • Tuple with collection val t = (1, List(1, 2, 3, 4))
  • Collection with tuple  val t = List((1, "Hello"), (2, "World"))
  • We will use tuples quite extensively in Spark as a key value pair

Example

import scala.io.Source
val orderItems = Source.fromFile("/data/retail_db/order_items/part-00000").getLines
orderItems.take(10).foreach(println)
val t = (1,1,957,1,299.98,299.98)
t._1
print(t)

Share this post