Scala Tuples

A tuple groups a fixed number of values of different types into a single unit. Unlike a List (which holds many values of one type), a Tuple can mix types. Tuples are useful when a function needs to return multiple values without defining a full class.

Creating Tuples

val pair = (42, "hello")                        // Tuple2[Int, String]
val triple = (1, true, "Scala")                 // Tuple3[Int, Boolean, String]
val person = ("Priya", 28, "Engineer", Mumbai") // Tuple4

// Arrow syntax for pairs (commonly used in Maps)
val coord = 10 -> 20   // same as (10, 20)

Accessing Elements

val point = (3.5, 7.2, "origin")

println(point._1)   // 3.5   (first element)
println(point._2)   // 7.2   (second element)
println(point._3)   // origin (third element)

Destructuring

val (x, y) = (10, 20)
println(s"x=$x, y=$y")   // x=10, y=20

val (name, age, city) = ("Ravi", 30, "Delhi")
println(s"$name, $age, $city")

// In a for loop
val pairs = List((1, "one"), (2, "two"), (3, "three"))
for (num, word) <- pairs do
  println(s"$num = $word")

Functions Returning Tuples

def minMax(nums: List[Int]): (Int, Int) =
  (nums.min, nums.max)

val (lo, hi) = minMax(List(3, 1, 9, 4, 7))
println(s"Min: $lo, Max: $hi")   // Min: 1, Max: 9

def divmod(a: Int, b: Int): (Int, Int) =
  (a / b, a % b)

val (quotient, remainder) = divmod(17, 5)
println(s"$quotient remainder $remainder")   // 3 remainder 2

Tuple vs Case Class


Tuple                           Case Class
───────────────────────────     ──────────────────────────────
Quick to write                  Named fields — more readable
Access by position (_1, _2)     Access by name (.name, .age)
No custom methods               Can have methods
Good for internal use           Good for public API / domain
(x, y) for coordinates          Point(x, y) for coordinates

Use tuples for ad-hoc grouping inside a function. Use case classes for data that crosses API boundaries or needs clear field names.

Leave a Comment

Your email address will not be published. Required fields are marked *