The in
operator is used to check if:
The in
operator will return true
for the above two cases; otherwise, it returns false
.
in
operator in for
loop:fun main(args : Array<String>) {for (i in 1..3){ //iterates loop from 1 toprintln(i)}val array = arrayOf(1, 2, 3, 4, 5);for (item in array) { //iterates all items in arrayprint(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.
in
in if:fun main(args : Array<String>) {val num = 10if (num in 1..10){ //iterates loop from 1 toprintln(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
.