In Operator (in and !in) in Kotlin

Definition

  • In operators are mainly used in when statements or expressions to check if a value falls in a range or a collection. 
  • This operator also has its use in for loop while iterating a collection.

Syntax

1. in Operator

if(value in collection){
	//Block of Code
}

For example,

if(value in collection){
	println("$value is available in collection")
}

1. !in Operator

if(value !in collection){
	//Block of Code
}

For example,

if(value !in collection){
	println("$value is not available in collection")
}

In and !in Operator Example Program in Kotlin

//In Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
    val collection = 10..20
    val num2 = 5

    println("in operator in if condition")
    if (15 in collection) {
        println("15 is in $collection")
    }

    println("\nin operator in for loop")
    for(item in collection){
        println("$item is in $collection")
    }

    println("\nin operator in when statement")
    when{
        19 in collection -> println("19 in collection is true")
    }
}

Sample Output

in operator in if condition
15 is in 10..20

in operator in for loop
10 is in 10..20
11 is in 10..20
12 is in 10..20
13 is in 10..20
14 is in 10..20
15 is in 10..20
16 is in 10..20
17 is in 10..20
18 is in 10..20
19 is in 10..20
20 is in 10..20

in operator in when statement
19 in collection is true