Cookie Preferences

We use cookies to enhance your experience. Choose your preference for cookie usage.

Essential cookies are required for basic functionality. Additional cookies help us improve our service and provide analytics.

View third-party services
  • Google Analytics: Website traffic analysis and conversion tracking
  • RudderStack: Analysis of user interactions with the website
  • Microsoft Clarity: User behavior analysis & session recordings
  • Facebook Pixel: Marketing analysis of user activity
KotlinStrings, arrays and ranges

Ranges

8 seconds read

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

If you need to check that a value is not within a range, just add ! (not) before in.

val notWithin = 100 !in 10..99 // true

You may combine ranges using standard logical operators. The code below checks that 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, it is also possible to 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

Now it is enough to understand only ranges for integer numbers and characters, ranges of other types won't be considered here.
How did you like the theory?
Report a typo