Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

koltin
operators
communitycreator

What is the "in" operator in Kotlin?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.


RELATED TAGS

koltin
operators
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring