What is the "in" operator in Kotlin?

The in operator is used to check if:

  • a value is present in the range.
  • the value is present in a collection.

The in operator will return true for the above two cases; otherwise, it returns false.

Example

Using in operator in for loop:

fun main(args : Array<String>) {
for (i in 1..3){ //iterates loop from 1 to
println(i)
}
val array = arrayOf(1, 2, 3, 4, 5);
for (item in array) { //iterates all items in array
print(item)
}
}

In the code above, we used i in 1..3, which means that, until the value of i is in the range of 1 to 3 (included), the for loop will be executed.

Similarly, item in array means the loop will execute until all the elements of the array are looped.

Using in in if:

fun main(args : Array<String>) {
val num = 10
if (num in 1..10){ //iterates loop from 1 to
println(num)
}
val array = arrayOf(1, 2, 3, 4, 5)
print("Checking if 10 present in array => ")
println(10 in array)
print("Checking if 5 present in array => ")
print(5 in array)
}

In the code above, we have created a num variable and checked if the value is in the range of 1 to 10. We have also created an array and checked if the array contains the 5 and 10.


Free Resources