Imagine a situation when you need to check whether 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 this:
val within = a <= c && c <= b
This code works well. However, Kotlin provides a more convenient way to do the same thing using ranges:
val within = c in a..b
a..b is a range of numbers from
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
c belongs to the range inclusively, otherwise, it is
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
If you need to check that a value is not within a range, just add
! (not) before
val notWithin = 100 !in 10..99 // true
You may combine ranges using standard logical operators. The code below checks if
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
You can assign a range to a variable and use it later.
val range = 100..200 println(300 in range) // false
In addition to integer ranges, you can also use ranges of characters and even strings (according to dictionary order).
println('b' in 'a'..'c') // true println('k' in 'a'..'e') // false println("hello" in "he".."hi") // true println("abc" in "aab".."aac") // false
This is enough to understand ranges for integer numbers and characters. We won't investigate ranges of other types here.