How to Use Step in Kotlin: Syntax and Examples
In Kotlin,
step is used with ranges or progressions to specify the increment between values in a loop or sequence. You add step(n) after a range to increase by n instead of the default 1.Syntax
The step function is used with ranges or progressions to define the increment between values. The general syntax is:
start..end step incrementHere:
start..enddefines the range of values.step incrementsets how much to increase each time.
kotlin
for (i in 1..10 step 2) { println(i) }
Output
1
3
5
7
9
Example
This example shows how to print numbers from 1 to 10, increasing by 2 each time using step. It skips every other number.
kotlin
fun main() {
for (i in 1..10 step 2) {
println(i)
}
}Output
1
3
5
7
9
Common Pitfalls
One common mistake is forgetting that step only works with ranges or progressions, not with plain lists. Also, using a step value of 0 or negative numbers without proper direction causes errors or unexpected behavior.
Another pitfall is using step with a decreasing range without specifying downTo.
kotlin
fun main() {
// Wrong: step with a list (won't compile)
// val list = listOf(1, 2, 3, 4, 5)
// for (i in list step 2) { println(i) }
// Correct: use step with a range
for (i in 5 downTo 1 step 2) {
println(i)
}
}Output
5
3
1
Quick Reference
| Usage | Description |
|---|---|
| start..end step n | Range from start to end, increment by n |
| start downTo end step n | Range from start down to end, decrement by n |
| step value must be > 0 | Step must be positive to avoid errors |
| Works only with ranges/progressions | Cannot use step directly on lists |
Key Takeaways
Use
step with ranges to control the increment in loops.Always ensure the step value is positive and matches the range direction.
step does not work on lists; use it only with ranges or progressions.For decreasing sequences, combine
downTo with step.Using
step helps skip values easily in loops.