until Tutorial 🎯Welcome to the Kotlin until tutorial! In this lesson, we'll learn about the until keyword in Kotlin, a powerful tool for working with ranges.
until keyword in Kotlin? 📝The until keyword in Kotlin is used to create a range up to a specific number, excluding the specified number itself.
until keyword? 💡The until keyword is useful when you want to loop through a range of numbers up to, but not including, a specific number. This can save you from having to manually check if the current number is within the specified range.
Let's see how to use the until keyword in a simple example.
fun main() {
for (i in 1..5) {
println(i)
}
println()
for (i in 1 until 5) {
println(i)
}
}In the above example, the first loop prints the numbers from 1 to 5 (inclusive). The second loop prints the numbers from 1 to 4 (exclusive), demonstrating the usage of the until keyword.
The until keyword can also be used with steps other than 1. Let's see an example:
fun main() {
for (i in 0 until 10 step 2) {
println(i)
}
}In this example, the loop starts from 0 and ends at 10, incrementing by 2 every time.
until with let and also 💡The let and also functions in Kotlin can be used with the until keyword to perform operations on a range.
fun main() {
(1..5).let { range ->
println("The range is $range")
}
(1 until 5).also { range ->
println("The range is $range")
}
}In the above example, both let and also are used to perform operations on the range created by 1..5 and 1 until 5. The difference between the two is that let returns the passed receiver, and also returns the receiver itself.
What does the Kotlin `until` keyword do?
What is the difference between using `let` and `also` with a range created by `until`?