Java和Kotlin的for循环语法差异

huangapple go评论52阅读模式
英文:

Difference between Java and Kotlin for-loop syntax

问题

我最近开始学习Kotlin,Kotlin的for循环语法与Java不同。

我应该如何在Kotlin中复制以下Java for循环?

fun funa(a: Int) {
    var i = 0
    var b = a
    while (b >= 1024) {
        b /= 1024
        i++
    }
    println("val $a steps $i")
}

我知道我可以像这样做:

fun funa(a: Long) {
    var b = a
    var i = 0
    while (b >= 1024) {
        b /= 1024
        i++
    }
}

但这看起来真的很愚蠢。

英文:

I recently started learning Kotlin and for-loop syntax of Kotlin is different from Java.

**How would I duplicate the following Java for loop in Kotlin?
**

void funa(int a){
  for(int i = 0; a >= 1024; i++){
    a /= 1024;
  }
  System.out.println("val " + a + " stesps " + i)
}

I know i can do something like this

fun funa(a: Long){
    var b = a
    var i = 0;
    while (b>= 1024){ 
        b /= 1024
        i++
    }
}

but it looks realy stupid

答案1

得分: 1

Kotlin不提供基于计数器的for循环,只提供for-each操作。在许多情况下,我们可以用for-each覆盖传统的循环,例如:

for (i in 0..8) { }

当然,在您的情况下,这是不可能的。在这种情况下,我们应该使用基于while的建议解决方案。

英文:

Kotlin does not provide the for loop based on a counter, but only the for-each operation. In many cases we can replace traditional loops with a for-each over a range, for example:

for (i in 0..8) { }

Of course, in your case this is not possible. In this case we should use your suggested solution based on while.

答案2

得分: 1

你的Java代码没有意义 - 要在循环后记录i,你必须在循环之前声明i,因此它应该如下所示:

int i = 0;
for (; a >= 1024; i++) {
    a /= 1024;
}
System.out.println("val " + a + " steps " + i);

这与以下代码看起来没有更愚蠢也不更聪明:

var i = 0
while (a >= 1024) {
    a /= 1024
    i++
}
println("val $a steps $i")

这只是不同的语法。可以争论Kotlin版本更容易阅读,代价是行数更多,因为它更加明确,没有在第一个;之前的奇怪空表达式。

Kotlin不支持for(;;)语法是一个设计决策。我认为他们的理由是这样的,它容易混淆。如果我们已经使用基于C语法的语言多年,这种语法可能不会显得混淆,但对于新手程序员来说,这种语法有很多要记住的单独元素,导致了复杂的行为组合。

在Java中,更常见的是使用repeat函数来简单地迭代预定次数:

repeat(10) { i ->
    println("Count $i")
}

或者如果你要迭代集合的索引:

for (i in list.indices) {
    println("Item $i is ${list[i]}")
}
英文:

Your Java code doesn't make sense--to be able to log i after the loop, you would have to declare i before the loop, so it would have to look like:

int i = 0;
for(; a >= 1024; i++){
    a /= 1024;
}
System.out.println("val " + a + " steps " + i);

That doesn't look any more or less stupid than:

var i = 0
while (a >= 1024) {
    a /= 1024
    i++
}
println("val $a steps $i")

It's just different syntax. It could be argued the Kotlin version is easier to read at the expense of number of lines, because it is more explicit and doesn't have the weird empty expression before the first ;.

It's a design decision that Kotlin doesn't have the for(;;) syntax. I think their reasoning is that it's confusing. It may not seem confusing if we've been using any C-syntax-based language for years, but to a brand new programmer, that syntax has a lot of individual elements to remember, contributing to a complex group of behaviors.

It's far more common for Java for-loops to simply be iterating something a pre-determined number of times. For that, you can use the repeat function:

repeat(10) { i ->
    println("Count $i")
}

Or if you are iterating a collection's indices:

for (i in list.indices) {
    println("Item $i is ${list[i]}")
}

</details>



# 答案3
**得分**: 0

诚实地说,你的提案已经看起来不错了。实际上,它比Java等效的更好,因为在Java中,你暗示计数器影响了循环条件,而事实并非如此。你只是想要计算步骤作为副作用。

---

在Kotlin中,你不能在这种用例中使用for循环,因为:

> for循环遍历任何提供迭代器的东西。[来源][1]

尽量不要过度设计,你已经有了适当的Kotlin代码。

[1]: https://kotlinlang.org/docs/control-flow.html#for-loops

<details>
<summary>英文:</summary>

Honestly, your proposal looks good already. It&#39;s actually better than the Java equivalent, because in that one you imply that the counter influences the loop condition which is not the case. You merely want to count the steps as a side-effect.

---

In Kotlin you cannot use a for loop for that use-case because:

&gt; for iterates through anything that provides an iterator. ([source][1])


Try not to overengineer things, you already have proper Kotlin code.

  [1]: https://kotlinlang.org/docs/control-flow.html#for-loops

</details>



huangapple
  • 本文由 发表于 2023年7月11日 04:17:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定