Working With Ranges in Kotlin
Kotlin provides a simple and intuitive way to create ranges.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Range from 1 to 5
fun createSimpleRange(): String {
var str = ""
for (i in 1..5) {
str += i
}
return str
}
// Range from 5 to 1
fun createDescendingRange(): String {
var str = ""
for (i in 5 downTo 1) {
str += i
}
return str
}
// Creates a range from 2 to 10 in steps of 2
fun createRangeWithStep(): String{
var str = ""
for (i in 2..10 step 2) {
str = "${str.trim()} $i"
}
return str
}
fun main(args: Array<String>) {
println(createSimpleRange())
// 12345
println(createDescendingRange())
// 54321
println(createRangeWithStep())
// 2 4 6 8 10
}
You can easily create ranges including ranges in reverse order as well as those with defined steps.