- 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 favourite 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 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.
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 which represents a range of dates.
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:
class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterator<MyDate> {
operator fun contains(d: MyDate) = start <= d && d <= endInclusive
}
With this new function, we can write our own in
statement, for example:
fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {
return date in DateRange(first, last)
}