I am just starting with Kotlin. I want to create range from 1 to n where n is excluded. I found out that Kotlin has ranges and I can use them as follows

1..n

但这是一个inclusive范围,包括1n.如何创建exclusive个范围.

推荐答案

Not sure if this is the best way to do it but you can define an Int extension which creates an IntRange from (lower bound +1) to (upper bound - 1).

fun Int.exclusiveRangeTo(other: Int): IntRange = IntRange(this + 1, other - 1)

And then use it in this way:

for (i in 1 exclusiveRangeTo n) { //... }

Here you can find more details about how ranges work.

Kotlin相关问答推荐

来自SnapshotFlow的单元测试StateFlow仅发出initialValue

等待下一个值时暂停Kotlin Coroutine

解决Microronaut中多个可能的Bean候选者冲突

Kotlin:有限的并行性并不是限制并行性

如何使用Kotlinx.LocalDateTime获取重置时间为00:00的当前日期?

kotlin短路列表判断吗?

限制通用Kotlin枚举为特定类型

有没有什么方法或算法可以在没有存储的情况下生成唯一的随机数?

如何在 Compose 中创建可重用的修饰符?

如何使用 Kotlin KClass 属性 simpleName 生成空值

将 Gradle 子元素与 Kotlin 多平台一起使用

Kotlin 单元测试 - 如何模拟 Companion 对象的组件?

ActivityOptions.makeSceneTransitionAnimation 在具有多个视图的 kotlin 中不起作用

如何在Spring Boot应用程序上启用承载身份验证?

使用范围的稀疏sparse值列表

用Gradle Kotlin DSL构建源jar?

uses-sdk:minSdkVersion 16 不能小于库中声明的版本 23

@StringRes、@DrawableRes、@LayoutRes等android注释使用kotlin参数进行判断

将协程更新到 1.2.0 后构建失败:META-INF/atomicfu.kotlin_module

可见性不适用于 Kotlin