Kotlin Starter Pack

romainbsl
8,426 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
2
9
10
11
12
13
14
15
// { autofold
fun checkRange(i: Int) {...}
fun main(args: Array<String>) {
checkRange(1)
checkRange(5)
checkRange(7)
checkRange(11)
}
//}
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
4
5
8
9
// {...}
for (i in 1..10 step 2) print(i)
// {...}
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