Learning Kotlin: The .. operator

Submitted by Robert MacLean on Thu, 08/23/2018 - 09:00
**More Information** * This is the 23rd post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction) * The code for this can be found [on GitHub](https://github.com/Kotlin/kotlin-koans/blob/master/src/iii_conventions/n27RangeTo.kt)

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:

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

If we add the rangeTo to the MyDate class and have it return a DateRange like this:

  1. data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) {
  2.     operator fun rangeTo(other: MyDate) = DateRange(this, other)
  3. }

We can now change our previous example to support the .. operator!

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

It compiles to the EXACT same code, but it just looks so much better!