我仍然认为使用for循环的"传统"方式非常强大,可以完全控制索引.为什么在Kotlin中删除它?
我应该如何在kotlin中使用以下java代码
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
....
Run Code Online (Sandbox Code Playgroud)
yol*_*ole 26
它没有被"删除".新语言的设计不是从任何现有语言的特征集开始; 我们从一种没有功能的语言开始,然后开始添加以一种不错的惯用方式表达某些行为所必需的功能.到目前为止,我们还没有意识到C风格的"for"循环是表达它的最好和最惯用的方式的任何行为.
Ale*_*nov 18
答案是:因为他们决定将其删除.您仍然可以使用以下语法:
for (a in 1..10) print("$a ") // >>> 1 2 3 4 5 6 7 8 9 10
for (a in 10 downTo 1 step 2) print("$a ") // >>> 10 8 6 4 2
Run Code Online (Sandbox Code Playgroud)
我认为他们这样做的原因("没有删除")是因为,他们想让Kotlin更具表现力.
例如,在java中我们可以像这样创建一个for循环:
for(int x = 1; x <= 10; x++) {
System.out.print(x);
}
Run Code Online (Sandbox Code Playgroud)
你要做的就是,你想要打印出1到10之间的值,就是这样.因此,Kotlin决定将您的单词翻译成代码并删除不必要的详细程度.
for (x in 1..10) print("$x")
Run Code Online (Sandbox Code Playgroud)
将这些索引保留为白色的另一种有用的迭代方法(即Iterable)是使用withIndex()
方法。例如:
for((i, element) in myIterable.withIndex()){
//do something with your element and the now known index, i
}
Run Code Online (Sandbox Code Playgroud)
我注意到该功能与该答案中所建议的功能相同,但我认为最好是使用Iterables在此类情况下已经内置的方法,而不是再次实现它们。我们可以说这也类似于forEachIndexed{}
lambda:
myIterable.forEachIndexed{i, element ->
//do something here as well
}
Run Code Online (Sandbox Code Playgroud)