Reputation: 13420
I would like to unpack tuples inside map
to access some of the values.
In Python I would do it this way:
>>> [topic for topic, partition in [('x', 1), ('y', 2)]]
['x', 'y']
Here tuples ('x', 1), ('y', 2)
are unpacked into topic, partition
, and then I access topic
.
In Scala I have only managed to make it this way:
List(('x', 1), ('y', 2)).map(_._1)
But I would like to have explicit unpack into tuple as an itermediate step (even if it introduces some overhead) as I think it makes the code more readable.
I would like to achieve something like
List(('x', 1), ('y', 2)).map((topic, partition) => topic)
Unfortunatelly it didn't work:
> <console>:9: error: wrong number of parameters; expected = 1
List(('x', 1), ('y', 2)).map((topic, partition) => topic)
Other attempts (e.g. List(('x', 1), ('y', 2)).map(Tuple2(topic, partition) => topic)
) also failed.
Is there any way to achieve something similar to what I have in Python?
Upvotes: 2
Views: 273
Reputation: 23881
Are you looking for this?
List(('x', 1), ('y', 2)).map {
case (topic, partition) => topic
}
Edit: one more way to do the same, as @senia suggested:
for {
(topic, partition) <- List(('x', 1), ('y', 2))
} yield topic
Upvotes: 4