Style question about flatMap identity

I have an object of type Set[Set[A]], and I would like a Set[A]. When I call obj flatMap identity I get exactly the set that I want. I find this idiom concise, perhaps as concise as possible, bordering on cryptic.

Another way to do the same thing in this case would be: obj.foldRight(Set[A]())(_ union _). I think the second better expresses what’s happening. But I don’t like having to put the additional [A] type indicator on the first argument.

I’d love to hear comments about which one better expresses the intent, and which one would be less shocking if someone reads my code at a later date.

For this simple use case, you can just use the flatten method:

Set(Set(1, 2), Set(2, 3, 4)).flatten // returns Set(1, 2, 3, 4)

It’s designed exactly for this use case, so it’s the clearest/most obvious choice IMO.

1 Like

Yes, that’s clearer. Thanks.