有没有更简洁的写作方式?
listOf('a'..'z','A'..'Z').flatMap { it }
The idea here is to iterate over some values in a range, like the numbers from 1 through 100, skipping 21 through 24
listOf(1..20, 25..100).flatMap { it }
有没有更简洁的写作方式?
listOf('a'..'z','A'..'Z').flatMap { it }
The idea here is to iterate over some values in a range, like the numbers from 1 through 100, skipping 21 through 24
listOf(1..20, 25..100).flatMap { it }
您可以使用flatten()
而不是flatMap()
来稍微缩短列表的长度:
listOf('a'..'z','A'..'Z').flatten()
or a shorter form (from @Ilya) is to use the plus()
+
operator of Iterable
(an interface that ranges implement). Each +
will make a copy of the list:
val validLetters = ('a'..'z') + ('A'..'Z')
val someNumbers = (1..20) + (25..100)
或者以Sequence
分的成绩更加懒惰(不确定在这里更懒惰是否重要):
sequenceOf('a'..'z','A'..'Z').flatten()
在Kotlin中,人们通常会创建一个helper函数来很好地包装这样的东西;如果您碰巧经常重用此代码:
// helper functions
fun sparseListOf(vararg ranges: CharRange): List<Char> = ranges.flatMap { it }
fun sparseListOf(vararg ranges: IntRange): List<Int> = ranges.flatMap { it }
...and the usage for those helpers:
val validLetters = sparseListOf('a'..'z', 'A'..'Z')
val someNumbers = spareListOf(1..20, 25..100)
NOTE: the helper functions use 100 since there is no 101 method or extension for 102 which is the type received from the 103. The lambda is inlined so likely there is no real difference in performance.