Kotlin 将 List<Triple<String, String, String> 变为 Triple<List<String>, List<String>, List<String>> 的优雅方式
Kotlin elegant way to mutate List<Triple<String, String, String> to Triple<List<String>, List<String>, List<String>>
我想尽可能简洁(但清晰)地将 List<Triple<String, String, String>
转换为 Triple<List<String>, List<String>, List<String>>
。
例如,假设执行转换的方法称为 turnOver
,我预计:
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
如何编写简洁、清晰且尽可能实用的 turnOver
函数?
可以用Arrow-Kt,我已经作为项目依赖获取了
fun turnOver(matches: List<Triple<String, String, String>>) = Triple(
matches.map { it.first },
matches.map { it.second },
matches.map { it.third },
)
我认为这是一个显而易见的解决方案。
据我所知,在 kotlin stdlib 中无法从可迭代对象、数组或序列中创建 Pair 或 Triple。我相信这是故意的。所以我想上面的那个是最清晰的解决方案。
我想尽可能简洁(但清晰)地将 List<Triple<String, String, String>
转换为 Triple<List<String>, List<String>, List<String>>
。
例如,假设执行转换的方法称为 turnOver
,我预计:
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
如何编写简洁、清晰且尽可能实用的 turnOver
函数?
可以用Arrow-Kt,我已经作为项目依赖获取了
fun turnOver(matches: List<Triple<String, String, String>>) = Triple(
matches.map { it.first },
matches.map { it.second },
matches.map { it.third },
)
我认为这是一个显而易见的解决方案。
据我所知,在 kotlin stdlib 中无法从可迭代对象、数组或序列中创建 Pair 或 Triple。我相信这是故意的。所以我想上面的那个是最清晰的解决方案。