Thursday, 10 September 2020

Scala: Tuple

Tuple is a collection of different type values.

 

Syntax

var/val tupleName = (val1, val2…valN)

 

Example

val person1 = (1, "Krishna", 5.8, "male")

Above statement define a tuple that store values of types Int, String, Double, String.

scala> val person1 = (1, "Krishna", 5.8, "male")
val person1: (Int, String, Double, String) = (1,Krishna,5.8,male)

How to access the elements of tuple?

Use _index method to access the elements of tuple. In tuples, index starts from 1.

scala> person1._1
val res210: Int = 1

scala> person1._2
val res211: String = Krishna

scala> person1._3
val res212: Double = 5.8

scala> person1._4
val res213: String = male

You can even use person1 _1 to access the 1st component of person1 tuple. To use this notation, you should import ‘scala.language.postfixOps’.

scala> import scala.language.postfixOps
import scala.language.postfixOps

scala> person1 _1
val res217: Int = 1

scala> person1 _2
val res218: String = Krishna

scala> person1 _3
val res219: Double = 5.8

scala> person1 _4
val res220: String = male

Access tuple elements using pattern matching

val (id, name, height, gender) = person1

Above statement maps 1st component of person1 to id, 2nd component to name, 3rd component to height and 4th component to gender.

scala> val person1 = (1, "Krishna", 5.8, "male")
val person1: (Int, String, Double, String) = (1,Krishna,5.8,male)

scala> val (id, name, height, gender) = person1
val id: Int = 1
val name: String = Krishna
val height: Double = 5.8
val gender: String = male

If you do not want to capture any value, use _.

scala> val (id, _, height, _) = person1
val id: Int = 1
val height: Double = 5.8



Previous                                                    Next                                                    Home

No comments:

Post a Comment