Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin elegant way to mutate List<Triple<String, String, String> to Triple<List<String>, List<String>, List<String>>

I'd like, as succinctly (yet clearly) as possible to transform a List<Triple<String, String, String> to a Triple<List<String>, List<String>, List<String>>.

For instance, say the method performing the transformation is called turnOver, I'd expect:

val matches = listOf(
  Triple("a", "1", "foo"),
  Triple("b", "2", "bar"),
  Triple("c", "3", "baz"),
  Triple("d", "4", "qux")
)
val expected = Triple(
  listOf("a", "b", "c", "d"),
  listOf("1", "2", "3", "4"),
  listOf("foo", "bar", "baz", "qux")
)
matches.turnOver() == expected // true

How to write a succinct, clear, and possibly functional turnOver function?

It's ok to use Arrow-Kt, I already got it as project dependency.

like image 671
Danilo Pianini Avatar asked Oct 29 '25 05:10

Danilo Pianini


1 Answers

fun turnOver(matches: List<Triple<String, String, String>>) = Triple(
   matches.map { it.first },
   matches.map { it.second },
   matches.map { it.third },
)

would be one obvious solution I reckon.

like image 50
fweigl Avatar answered Oct 31 '25 00:10

fweigl