Scala Language Extractors Tuple Extractors

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

x and y are extracted from the tuple:

val (x, y) = (1337, 42)
// x: Int = 1337
// y: Int = 42

To ignore a value use _:

val (_, y: Int) = (1337, 42)
// y: Int = 42

To unpack an extractor:

val myTuple = (1337, 42)
myTuple._1  // res0: Int = 1337
myTuple._2  // res1: Int = 42

Note that tuples have a maximum length of 22, and thus ._1 through ._22 will work (assuming the tuple is at least that size).

Tuple extractors may be used to provide symbolic arguments for literal functions:

val persons = List("A." -> "Lovelace", "G." -> "Hopper")
val names = List("Lovelace, A.", "Hopper, G.")

assert {
  names ==
    (persons map { name =>
      s"${name._2}, ${name._1}"
    })
}

assert {
  names ==
    (persons map { case (given, surname) =>
      s"$surname, $given"
    })
}


Got any Scala Language Question?