Hacking with Kotlin: ranges

As you may know, C# 8 introduces bounded ranges.

The syntax looks like this:

Can we achieve the same with Kotlin?

Of course we can!

We’ll start with a list:

But there’s nicer syntax for that already:

And there’s already subList() function available:

Let’s first make it work with the following syntax:

For that we’ll use extension function that accepts range of integers:

As you can see, 3..5 is just a ClosedRange that has start and endInclusive members

Now the following code should work:

Next we want the following nice syntax to work too:

For that we’ll have another extension function:

Since square brackets are special symbols, we mark this function as operator to be able to use them.

And we simply delegate the logic to the first function we had written.

We can also make it even shorter:

And now, we’re in C# 8 land:

No need to wait for the next major version of your favorite language.

Happy Kotlin, and stay tuned for next post in series!

Solutions Architect @Depop, author of “Hands-on Design Patterns with Kotlin” book and “Web Development with Kotlin” course