How do you use 'Tuples' in Scala?
Instruction: Discuss the purpose of tuples in Scala and how to utilize them in Scala applications.
Updated
A tuple groups a fixed number of values whose types can differ. It is useful for a small, local result with several components. Access components by position or destructure the tuple into named local bindings.
def labelAndCount(names: List[String]): (String, Int) =
(names.headOption.getOrElse("none"), names.size)
@main def tuplesExample(): Unit = {
val result = labelAndCount(List("Ada", "Lin"))
val (first, count) = result
assert(first == "Ada" && count == 2)
assert(result._1 == "Ada" && result._2 == 2)
assert(labelAndCount(Nil) == ("none", 0))
val buffer = scala.collection.mutable.ArrayBuffer(1)
val pair = ("items", buffer)
buffer += 2
assert(pair._2.toList == List(1, 2))
}
The tuple's component bindings are immutable, but an object referenced by a component can still mutate, as the buffer shows. A tuple is therefore not automatically a deeply immutable snapshot. Tuples and destructuring
Use a case class when names and domain meaning matter across an API, for example case class Summary(first: String, count: Int). Large positional tuples can become hard to read and easy to mix up. Tuples avoid defining a new data class for a small local grouping, but they do not imply that no object is allocated or that they outperform an equivalent class; measure relevant workloads before making that claim.