Kotlin Starter Pack

romainbsl
2,769 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Ranges

Kotlin provide a way to deal with value ranges, so you might be able to simply create and manipulate ranges effortlessly.

Control if a value belong or not to a range of elements.

1
4
5
6
7
// {...}
if (i in 1..10) { // equivalent of 1 <= i && i <= 10
println("$i belongs to the range 1..10")
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Iteration over ranges

1
4
5
// {...}
for (i in 1..5) println("square($i) gives ${i * i}")
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Reverse iteration over ranges

1
4
5
// {...}
for (i in 5 downTo 1) print(i)
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Iterating over ranges ... step by step

1
2
3
4
5
6
7
8
9
// { autofold
fun main(args: Array<String>) {
//}
for (i in 1..10 step 2) print(i)
// { autofold
println()
// }
for (i in 10 downTo 1 step 2) print(i)
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Range with exclusion

1
4
5
// {...}
for (i in 1 until 5) print(i)
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content