元組提取器

xy 是從元組中提取的:

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

要忽略值,請使用 _

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

要解壓縮提取器:

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

請注意,元組的最大長度為 22,因此 ._1._22 將起作用(假設元組至少是那個大小)。

元組提取器可用於為文字函式提供符號引數:

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"
    })
}