I want to print 0001 (note the 3 preceding 0s), and incremental 1 at a time, and reach 1000 to stop. How could I do that in Kotlin without complex appending the 0s myself?

The below is not helping as it will not have preceding 0s.

for (i in 1..1000) print(i)

推荐答案

You can use padStart:

(0..1000)
    .map { it.toString().padStart(4, '0') }
    .forEach(::println)

It’s part of the Kotlin Standard Library and available for all platforms.

Kotlin相关问答推荐

Jetpack Compose中的数字 Select 器问题

如何确保Kotlin子类已完成初始化?

如何在Kotlin中为接受varargs的函数添加带有默认值的新参数?

Kotlin中函数引用的否定

扩展属性委托给实例属性

用于将 0.5 变为 0 的 round() 函数的模拟

如何将 `when` 与 2 个密封类一起使用并获取内部值?

使用 kotlin 流删除 map 中具有某些相似性的值

Kotlin 如何使用其 get 函数在内部检索映射值

如何从kotlin中的ArrayList中删除所有元素

Kotlin 具体化的泛型不会按计划保持类型

更新到版本4.10.1/4.10.2后 Gradle 同步失败

未找到导入 kotlinx.coroutines.flow.*

Android插件2.2.0-alpha1无法使用Kotlin编译

在 gradle android library kotlin 项目中禁用 META-INF/* 生成

如何为 Java 调用者声明返回类型为void的 Kotlin Lambda?

这是 Kotlin 中的错误还是我遗漏了什么?

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

Kotlin 是否支持部分应用程序?

在 intelliJ 元素中集成 Kotlinx 协程