Wednesday, 27 September 2017

9)Tuples in scala

Tuples in scala:
Tuple is the collection class in Scala which can hold multiple values with same or different types together.

Syntax:
tuples are declared within braces "()"

Note:
tuple can hold up-to 22 values/elements, since the scala compiler is smart enough, so dont need to specify the lengh explicitly.
tuple1,tuple2.....tuple22
Useful at below situations:

  • if you want a common reference
    • Ex: student details like name,age, etc.,
  • Performance wise is better than list

Example:
Student details with three elements


Note:
.getClass function is used to return data type of variable
Access values of Tuple in Scala:
To access values inside the tuple is through position of elements _1,_2,......_22.

Syntax:
<<tuple_variable>>._1
<<tuple_variable>>._2
<<tuple_variable>>._3...etc
Example:
val studentname = studentinfo._1


Assign values of tuples to multiple variables in one line:
We can also assign the tuple values to multiple variables at once

Syntax:
val (var1,var2,...) = tupleholder
Example:













5 comments:

Fundamentals of Python programming

Fundamentals of Python programming: Following below are the fundamental constructs of Python programming: Python Data types Python...