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++) {
....
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.
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.
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.
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
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With