Named Tuples in Scala 3.7.0

Published 2025-05-09
scalacode

I've been longing for named tuples in Scala for quite some time. Regular tuples often lead to unreadable code and maintenance issues, especially when used outside the IDE. Thankfully, SIP-58 - Named Tuples was included in 3.7.0 release of Scala.

Named tuples adds labels to tuple elements, allowing name-based access like .foo instead of relying on index-based access like ._1.

So after upgrading the current project I'm working on, I'm able to apply named tuples. I really think it has a great impact on the code base.

Just to give an example of what some typical code could look like (just over simplified) before.

class FooBarRepo:
  def getFooBar(id: FooBarId): (Foo, Bar) = ???

So whenever I used the FooBarRepo.getFooBar-method I had to make sure that I used the right index, _1 or _2, to get Foo or Bar. It works in an IDE, but it's hard to read elsewhere like in diffs, documentation or pull requests.

Here is an example:

val fooBar = fooBarRepo.getFooBar(id)
val fooName = fooBar._1.name
val barName = fooBar._2.name

So reading the _1 and _2 always makes me worried. Is it the right one? Has anyone changed it? Here can small refactorings break assumptions and silently introduce bugs.

An alternative would have been to introduce a case class like:

case class FooBar(foo: Foo, bar: Bar)

The downside is introducing a class that's only used once place. I find it a bit cumbersome, and that is why a tuple is used in the first place.

After upgrading to Scala 3.7.0 I changed the FooBarRepo code to:

class FooBarRepo:
  def getFooBar(id: FooBarId): (foo: Foo, bar: Bar) = ???

Here I'm adding foo: and bar: to the regular tuple (Foo, Bar) to convert it to the named tuple (foo: Foo, bar: Bar).

That means that I was able to change the rest of the code to:

val fooBar = fooBarRepo.getFooBar(id)
val fooName = fooBar.foo.name
val barName = fooBar.bar.name 

I think this makes the code easier to read and reason about, especially outside the IDE. Now I no longer worry about anyone accidentally introducing bugs by making changes to the tuple structure.

Named tuples brings a lot more to the table than I've shown. I'm really excited to see how that will impact my code going forward.

Have you started using named tuples in Scala 3.7? I’d love to hear how it's changing your code.

Tilbake til bloggen