有没有更简洁的写作方式?

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.

Kotlin相关问答推荐

Kotlin—从列表中枚举属性计算不同值的数量

Kotlin异步不并行运行任务

Scala与Kotlin中的迭代

创建包含 3 个相同项目的列表/使用返回类型重复

如何将光标从一个文本字段传递到 Jetpack Compose 中的其他文本字段?

jlink:在合并模块和 kotlin.stdlib 中打包 kotlin.*

如何在 micronaut 上启用 swagger UI?

Lets plot Kotlin中的多轴比例

如何在 jOOQ 中两次加入同一张表?

如何通过 compose 处理剪切区域?

是什么让 Kotlin 中的 String 类能够使用方括号?

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

Kotlin JVM 和 Kotlin Native 有什么区别?

从片段(fragment)中的点击事件启动协同程序

(kotlin的Moshi)@Json vs@field:Json

使用导航组件在BottomNavigationView中传递参数

从命令行运行Java到Kotlin转换器?

Gradle:无法连接到 Windows 上的 Kotlin 守护程序

Kotlin - 具有私有构造函数的类的工厂函数

使用 rxbinding 时我应该取消订阅吗?