Suppose a situation when you need to check the integer variable c
is greater than or equal to a
and less than or equal to b
. To do that you may write something like below:
val within = a <= c && c <= b
This code works well. But Kotlin provides a more convenient way to do the same using ranges:
val within = c in a..b
Here, a..b
is a range of numbers from a
to b
(inclusive both borders), in
is a special keyword that is used to check whether a value is within a range. Later you will see that this keyword can be used with other types, as well.
The value of within
is true
if c
belongs to the range inclusively, otherwise, it is false
.
Here are some examples:
println(5 in 5..15) // true
println(12 in 5..15) // true
println(15 in 5..15) // true
println(20 in 5..15) // false
If you need to exclude the right border, you may subtract one from it:
val withinExclRight = c in a..b - 1 // a <= c && c < b
!
(not) before in
.val notWithin = 100 !in 10..99 // true
c
is within one of three ranges.val within = c in 5..10 || c in 20..30 || c in 40..50 // true if c is within at least one range
val range = 100..200
println(300 in range) // false
println('b' in 'a'..'c') // true
println('k' in 'a'..'e') // false
println("hello" in "he".."hi") // true
println("abc" in "aab".."aac") // false