Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was the indexed for loop removed in Kotlin?

I still think "traditional" way of using the for loop is very powerful with full control of the index. Why was it removed in Kotlin?

what should I do in kotlin with following java code

for (int i = 0; i < n - 1; i++) {
   for (int j = i + 1; j < n; j++) {
   ....
like image 758
王子1986 Avatar asked Jul 17 '17 12:07

王子1986


People also ask

Is there a for-loop in Kotlin?

In Kotlin, the for loop is used to loop through arrays, ranges, and other things that contains a countable number of values. You will learn more about ranges in the next chapter - which will create a range of values.

What does indices mean in Kotlin?

indices returns IntRange (range of index from first to the last position) of collection, for example: val array= arrayOf(10,20,30,40,50,60,70) println("Indices: "+array.indices) // output: Indices: 0..6.

How do you reset the loop on Kotlin?

You should use a regular for-loop that ranges from 0 to length-of-S2 in the inner for-loop, and just reset the iterator variable to 0 when you want to "reset" the for-loop.


3 Answers

The answer is: because they decided to remove it. You can still use this syntax:

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 

For more info: Ranges & Loops

like image 179
Alexander Romanov Avatar answered Oct 21 '22 05:10

Alexander Romanov


It was not "removed". The design of a new language doesn't start with the feature set of any existing language; we start with a language that has no features, and start adding features which are necessary to express certain behavior in a nice and idiomatic way. Up until now, we aren't aware of any behavior for which a C-style 'for' loop would be the nicest and most idiomatic way to express it.

like image 28
yole Avatar answered Oct 21 '22 03:10

yole


Another useful way of retaining those indexes white iterating something (an Iterable, that is), is to use the withIndex() method. For example:

for((i, element) in myIterable.withIndex()){
    //do something with your element and the now known index, i
}

This I noticed achieves the same as what suggested in this answer, but I think it is better if we use the already built-in method Iterables have for such situations instead of implementing them again. This we could say is also similar to the forEachIndexed{} lambda:

myIterable.forEachIndexed{i, element ->
    //do something here as well
}
like image 10
DarkCygnus Avatar answered Oct 21 '22 04:10

DarkCygnus