1. Overview

In this tutorial, we’ll discuss the operator denoted by “..<“, which has reached a stable state with the release of Kotlin version 1.9.0-RC. With this new feature, we can generate range expressions that exclude the end limit in a straightforward and concise manner.

2. Open-Ended Range Operator

We can use the “..<” operator to create a range of objects by specifying two bounds: the starting bound, which is inclusive, and the ending bound, which is exclusive. 

While we were already familiar with the “..” operator for creating closed-ended ranges, the introduction of the “..<” enables us to create ranges in a similar manner, but with the end limit excluded. For instance, let’s utilize it to form an IntRange containing the numbers between two and five:

val numbers : IntRange = 2..<5
assertEquals(numbers.toList(), listOf(2,3,4))

Since the resulting object is a range, we can use the new operator when defining a for loop. Let’s use it to iterate through characters between ‘a‘ and ‘d‘:

val chars = ArrayList<Char>()
for (ch in 'a'..<'e') {
    chars.add(ch)
}

assertEquals(chars, listOf('a', 'b', 'c', 'd'))

As we can observe, “..<” provides an equivalent functionality to the until keyword. One of the primary reasons for introducing this alternative was the ambiguity associated with the until keyword, which fails to convey whether the upper bound is inclusive or exclusive.

3. Conclusion

In this concise article, we explored the operator denoted by “..<“, which became stable with Kotlin version 1.9.0-RC. This operator simplifies the process of creating ranges and making it effortless to exclude the end limit.

As always, the full source code of the examples is available over on GitHub.
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.