‘in’ operator in Kotlin


‘in’ operator in Koltin is used to check the existence of particular variable or property in a Range or Collection whereas a ‘!in’ operator is just a not of ‘in’ operator and returns true if the condition is false. It can also be used to iterate over a range or collection.

1. ‘in’ operator in ‘if’ condition

  
val count = 5;
if (count in 1..10 && count !in 5..7) {
print(“Number is between range 1 to 10 but not between 5 to 7”)
}

val array: IntArray = intArrayOf(1, 2, 3, 4, 5)
if (count in array) {
print(“Number is present in property array”)
}

2. ‘in’ operator in ‘when’ condition

  
when (count) {
in 11..20 -> print(“Number is between 10 and 20 including both”)
!in 21..30 -> print(“Number is not between 21 to 30”)
in array -> print(“Number is present in property array”)
!in array -> print(“Number is not present in property array”)
}

3. ‘in’ operator in ‘for’ loop

  
for (item in 1..10){
print(“iterates loop from 1 to 10”)
}

for (item in array){
print(“iterates all items in array”)
}