How to assign Scala tuple fields to variable/value names

As a quick note, I was just reminded that when you have a Scala tuple instance, you can assign the tuple fields to Scala values. This tends to be more readable than accessing the tuple elements using the underscore syntax.

For example, if you have a Scala function like this that returns a tuple:

def getUserInfo = {
    // do some stuff here, then return a tuple (a Tuple3 in this case)
    ("Al", 42, 200.0)
}

you can assign the tuple fields to Scala val fields like this:

val(name, age, weight) = getUserInfo

If you paste all of that code into the Scala REPL, you’ll see this result after the last line:

scala> val(name, age, weight) = getUserInfo
name: String = Al
age: Int = 42
weight: Double = 200.0

That shows you that the tuple fields have been assigned to the Scala variables values, and you can further demonstrate that like this:

scala> name
res0: String = Al

scala> age
res1: Int = 42

scala> weight
res2: Double = 200.0

As I mentioned, I think that’s preferable to this approach of using the tuple underscore syntax:

scala> val t = getUserInfo
t: (String, Int, Double) = (Al,42,200.0)

scala> t._1
res3: String = Al

scala> t._2
res4: Int = 42

scala> t._3
res5: Double = 200.0

That approach is okay for some things, but in general I prefer to assign the tuple fields to named Scala values.

For more information on tuples, see my Scala tuple examples and syntax tutorial.