![]() ![]() ![]() So, we can iterate through it using for loop. Remember we can iterate through anything using kotlin for loop if it provides iterator. Or there might be the risk of updating the loop counter accidentally, making a typo for a different variable. In Kotlin, you can use for loop to iterate through following things Range Array String Collection. Java equivalent code only jumps over single. (If your Java example was long and complex, it might be easy to miss the update to i inside the loop, and assume from the top of the loop that it was only ever incremented by 1 each time. As you can see, Kotlin expects to exit the loop right after index childrenCount condition gets reached. This is for the same reason: lambda parameters (whether called it, or named explicitly) are read-only.Īnd to anticipate your next question: I don't think there's an official word on why for indexes, like function parameters, are read-only, but I suspect it's because having them mutable can lead to confusion and other errors. Unfortunately, there's no easy way to wrap this into a general higher-order function (which is how Kotlin allows many other language constructs to be faked^H^H^H^H^Himplemented). A for loop over a range or an array is compiled to an index-based loop that does not create an iterator object. And the loop variable is no longer restricted to the scope of the loop itself, which pollutes the namespace of the enclosing function/block and risks confusion later (especially if the variable is reused, as above).īut it's much more general: the loop variable can be adjusted by any amount each time through the loop, even in a way not known before-hand. ![]() Otherwise, I'm afraid the general case is simply to use a while loop instead, as you suggest: var i = 1Īs you say, this of course more awkward: the initial value, increment/decrement, and final value are now in three different places, and so the loop is harder to read. This can make the loop clearer and more concise but it only applies in some specific cases. First, in some cases you may be able to include the jumps in the iteration itself - perhaps iterating over the result of some process, instead of over a simple range. As you've found, the index of a …in… for loop is read-only in Kotlin you can't change it within the loop. Returns a lazy Iterable that wraps each element of the original array into an IndexedValue containing the index of that element and the element itself. ![]()
0 Comments
Leave a Reply. |