- This is the 23rd post in a multipart series.
If you want to read more, see our series index - The code for this can be found on GitHub
No, I didn’t forget what this operator is and just put two dots in place of it. The operator we are looking at is really ..
! This operator pairs very nicely with the in
operator we looked at previously in that it allows us to very easily create an instance of a class which can define a range. Let us look at a real example we have used already to help clear that up 1..10
.
What we have in that is an Int, then the operator, then another Int and when we do that, we get an instance of ClosedRange<Int>
. This is done by saying if you ask for a range of Ints, you get a different class which knows how to store the start and end Ints and work out the parts in that range. This is done with the rangeTo
operator function which is added to the Int class.
In the same way that Ints support this, we can use it too. If we look at the previous post about the in
operator, you can see we are using a custom class called MyDate
to represent a date value and we also have a DateRange
class to represent the start and end dates and we could check if a value fell in that range with this code:
fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {
return date in DateRange(first, last)
}
If we add the rangeTo
to the MyDate
class and have it return a DateRange
like this:
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) {
operator fun rangeTo(other: MyDate) = DateRange(this, other)
}
We can now change our previous example to support the ..
operator!
fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {
return date in first..last
}
It compiles to the EXACT same code, but it just looks so much better!