Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a list deconstruct like a tuple, or make a tuple iterate like a list, in scala

Tags:

scala

I've got some variables, and I want to create new variables by running each of them through a function. So essentially I've currently got

val formatted1 = format(raw1)
val formatted2 = format(raw2)
val formatted3 = format(raw3)

Is there any way to do this all in one line? Looking for something like

val (formatted1, formatted2, formatted3) = (raw1, raw2, raw3).map(format)

but that seems to combine features of a List and features of a Tuple in incompatible ways.

like image 520
Dax Fohl Avatar asked Sep 02 '25 06:09

Dax Fohl


1 Answers

You can map over tuple, but if you put your items in List:

val List(formatted1, formatted2, formatted3) = List(raw1, raw2, raw3).map(format)

This works with many other collections, like Seq, Array and so on (types on both sides has to be the same! but you can have more general type on the left: e.g. val Seq(...) = List(...)).

For Lists (but not for other types) you can also write something like this:

val formatted1::formatted2::formatted3::Nil = List(raw1, raw2, raw3).map(format)

Starting from Scala 2.10 you can perform same trick with Seq:

val formatted +: formatted2 +: formatted3 +: _ = ....
like image 99
om-nom-nom Avatar answered Sep 05 '25 00:09

om-nom-nom