Learning Kotlin: Looking at the In Operator & Contains

Note * This is the 22nd post in a multi-part series. If you want to read more, see our series index. * The code for this can be found here.

One of my absolute favorite features in Kotlin is ranges. You can easily go 1..10 to get a range of numbers from one to ten. In addition, so much of the way I find I want to work with Kotlin is around working with collections like lists and arrays. With all of those, we often want to know when something exists inside the range or the collection—and that’s where the in operator comes in. In the following example, we use the in operator to first check for a value in an array, then in a range, and then a substring in a string; each example below will return true:

val letters = arrayOf("a", "b", "c", "d", "e")
println("c" in letters)
println(5 in 1..10)
println("cat" in "the cat in the hat")

Naturally, Kotlin lets us add this to our classes too. The example from the Koans starts with a class that represents a range of dates:

class DateRange(val start: MyDate, val endInclusive: MyDate)

We then add an operator function named contains that checks if the value provided falls between the two dates of the class:

class DateRange(val start: MyDate, val endInclusive: MyDate) {
    operator fun contains(d: MyDate) = d in start..endInclusive
}