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.
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 +: _ = ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With