我正在尝试习惯 Kotlin 中的习语和快捷方式,我想知道是否有任何方法可以做到这一点。
val pairList = listOf(Pair(1, 2), Pair(5, 10), Pair(12, 15))
val firstList = // should be [1, 5, 12]
Run Code Online (Sandbox Code Playgroud)
或者一般来说,任何具有任何成员变量的类。我目前有:
val pairList = listOf(Pair(1, 2), Pair(5, 10), Pair(12, 15))
val firstList = ArrayList<Int>()
pairList.forEach { firstList.add(it.first) }
Run Code Online (Sandbox Code Playgroud)
小智 9
这是: val firstList = pairList.map { it.first }
first代表一对的第一个成员,当然还有second第二个成员
同样firstList适用于:
val pairList = listOf(Pair(ClassA(), ClassB()), Pair(ClassA(), ClassB()), Pair(ClassA(), ClassB()))
Run Code Online (Sandbox Code Playgroud)