You can also name the parts of the tuple you're assigning to, as in:
val (ID, Name) = (5, "Prashant")
assertEquals( 5, ID )
You can also use this like:
val (ID, Name, Age) = functionThatReturnsATuple3
println("ID: " + ID + ", age: " + Age)
When I first read about the _x
syntax I thought it was great and used it a lot. I've since basically stopped using it as when I have to look at code I wrote two months ago I have to spend a load of time trying to work out what the types of the _1
, _2
etc. are. I suppose it's obvious in hindsight that id
is much more readable than pair._1
.
This can also be used inside functions like map
, filter
etc. like:
val list: List[ (Int, String, Double) ] = ...
list map { case (id, name, time) => ... }
list filter { case (_, name, _) => name == "X" }
Note that in the filter
you can use _
s for elements which you aren't going to use in the body of the function. This can be useful when skimming over code like that to establish what parts of structures are being used and how values are built up.