https://kotlinlang.org logo
#announcements
Title
# announcements
d

dumptruckman

04/14/2020, 7:40 PM
I need to create a list of all the `m`’s produced by this cartesian product. Is there a nice idiomatic way to do this? Am I missing some kind of built in cartesian product function?
Copy code
messages.forEach { message ->
            recipients.forEach { recipient ->
                val m = messagingService.recordMessage(message, listOf(recipient))
            }
        }
I did this but it feels kind of gross
Untitled
Ah, this is much better but I still feel like it could be better…
m

Milan Hruban

04/14/2020, 8:43 PM
one solution that comes to mind is to wrap it into
buildList
and just call
add(m)
h

Hullaballoonatic

04/14/2020, 10:13 PM
I imagine the best way to handle cartesian product cleanly is to just make a generic method for it. do it the ugly but efficient way and hide it in some other file. ezpz
k

Kroppeb

04/15/2020, 1:17 AM
Change the first
map
to a
flatmap
and remove the
flatten
r

Roger Home-Martinsen

04/15/2020, 5:56 AM
I would make something like this. You could also consider making it an extension method on IterableX1
👍 1
e

EyeCon

04/16/2020, 9:16 AM
Replacing
Copy code
Pair(first, second)
with
Copy code
first to second
might be more idiomatic.
👍 1
3 Views