Learning Kotlin: Looking at the In Operator & Contains

Submitted by Robert MacLean on Tue, 08/21/2018 - 09:00

More Information

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

One of my absolute favourite features in Kotlin are 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 is 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, then a substring in a string; each example below will return true.

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

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

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

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

  1. class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterator<MyDate> {
  2.     operator fun contains(d: MyDate) = start <= d && d <= endInclusive
  3. }

With this new function we can write our own in statement, for example:

  1. fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {
  2.    return date in DateRange(first, last)
  3. }