如何在 Kotlin 中制作传统的 for 循环

Dav*_*nan 3 for-loop kotlin

JavaScript

for (var x = 0; x < 360; x += 0.5)
{
  // ...
}
Run Code Online (Sandbox Code Playgroud)

我如何在Kotlin 中做到这一点?


请注意,我的步长是浮点数,因此常规范围不起作用:

for (x in 0.0 until 360.0 step 0.5) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

我还需要排除结束值,因此为什么我使用until.


我现在将使用 while 循环:

var x = 0.0;

while (x < 360.0) {
  // ...
  x += 0.5
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*dam 5

现在在 Kotlin 中没有办法做到这一点,因为 Kotlin 没有“传统”for循环。我相信您选择while循环是正确的。事实上,传统的for循环只是while伪装的循环:

for (init; condition; post;) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

随时可以改写,

init
while (condition) {
    // do something
    post
}
Run Code Online (Sandbox Code Playgroud)

行为没有变化,因为 init 语句将始终执行,并且在循环运行甚至一次之前将始终检查条件。这个构造不能给你的一件事是一个仅作用于这个块的变量。如果你真的追求这种行为,下面的方法会起作用,尽管它不是很惯用。

for (x in generateSequence(0.0) { it + 0.5 }.takeWhile { it < 360.0}) {
    println(x)
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 Sequence,您可能还对更惯用的内容感兴趣forEach

generateSequence(0.0) { it + 0.5 }.takeWhile { it < 360.0 }.forEach { x ->
    // do something
}
Run Code Online (Sandbox Code Playgroud)