home search about rss feed twitter ko-fi

Tuples (Scala 3 Video)

A Scala tuple is a collection of two or more elements, and those elements can be of any type.

Tuples are created as values in between parentheses:

(1, 2.2, 3L, 'a', "yo")    // (Int, Double, Long, Char, String)

Access tuple elements in Scala 3 by their index:

val t = (1, 2.2, 3L, 'a', "yo")
t(0)
t(1)

Can also do this:

val (i, d, l, c, s) = (1, 2.2, 3L, 'a', "yo")

When it makes sense, you can use a tuple instead of a class:

// [1] class
case class Person(firstName: String, lastName: String)
val a = Person("Walter", "Bishop")

// [2] tuple
val b = ("Walter", "Bishop")

Functions can return tuples, which you can assign to variable names:

def getUserInfo: (String, Int, Double) =
    // do some stuff here, then return a 3-element tuple
    ("Al", 42, 200.0)

val (name, age, weight) = getUserInfo

// result:
// val name: String = Al
// val age: Int = 42
// val weight: Double = 200.0

Update: All of my new videos are now on
LearnScala.dev