
1. Overview
In this article, we will discuss kotlin loop until with examples.
2. Kotlin loop until
You can use until with your for loop to iterate a range of elements from an element up to another element. The syntax of the until is:
for (i in 1 until 10) { print(i) }
Note that the until does not include the end element.
The below for loop iterates from the element at index 0 to the element at index 4. But doesn’t include the element at index 5 (end element).
fun main() { val toys = arrayOf(0,1,2,3,4,5) for(toy in 0 until 5) { print(toys[toy] + " ") / * prints 0 1 2 3 4 */ } }
3. Use of Kotlin until in for loop
Assume you own a toy shop and have a few toys. You have an application to manage those toys. Each toy has a name, type, and stock status. You can iterate through the toys list by using for loop as below. This for loop iterates all the elements in the toys array.
data class Toy(val name: String, val type: String, var isInStock: Boolean) fun main() { val toys = arrayOf(Toy("Car", "Indoor", true), Toy("Slider", "Outdoor", true), Toy("Rider", "Outdoor", true)) for(toy in toys) { println(toy) } } Result: Toy(name=Car, type=Indoor, isInStock=true) Toy(name=Slider, type=Outdoor, isInStock=true) Toy(name=Rider, type=Outdoor, isInStock=true)
Now think that you have thousands of toys in your shop but you want to process only 10 toys at a time and not everything. Therefore, you can use until to limit the processing range as below:
for(index in 0 until 10) { println(toys[index]) }
The above for loop will process the toys from index 0 to index 9.
But if the to index
is less than or equal to the start index
, then the returned range is empty. So the for loop doesn’t execute at all.
The below for loop will never execute as the start index
0 is equal to the to index
0.
fun main() { val foo = arrayOf(0,1,2,3,4,5) for(i in 0 until 0) { println(foo[i]) } }
4. until to iterate except the last element
You can use until to iterate the entire collection except for the last element.
The below for loop iterates all the elements of collection a
except for the last element.
for(i in 0 until a.size - 1) { println(a[i]) }
5. until to iterate the complete list
You can iterate the entire collection using until. However, it is possible to iterate the entire collection even without using until.
The below for loop iterates all the elements of a
collection.
for(i in 0 until a.size) { println(a[i]) }
6. Conclusion
In this article, we have discussed the Kotlin loop until with unique examples. See our article kotlin for with index to find out the choices to iterate a collection with index.
Pingback: kotlin for with step for iterating the elements - TedBlob
Pingback: Kotlin ternary operator example: If-else conditional statement - TedBlob
Pingback: Kotlin range exclusive using until and extension function - TedBlob
Pingback: "Kotlin en boucle jusqu'à" Code Réponse's - Coder les réponses