Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Learning Kotlin: Looking at the In Operator and Contains

DZone's Guide to

Learning Kotlin: Looking at the In Operator and Contains

Want to learn more about using the in operator and contains in Kotlin? Check out this post to learn more and check out this sample code!

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

This is the 22nd post of this multipart series on learning Kotlin. If you want to read more, see our series index. The code for this can be found here.

One of my absolute favorite 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.

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 own classes, too. The example from the Koans starts with a class that 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)
}


How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
kotlin ,java ,contains ,tutorial ,operator ,in ,in operator

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}