Kotlin – Check if specific Value is in Range

Check if specific value is in the given range in Kotlin

To check if a specific value is in the given range in Kotlin, call contains() function on the range object. If the specified value is present in the range, then the function returns true, else it returns false.

The syntax to check if value value is in the range myRange is

if ( myRange.contains(value) ) {
  //your code
}

Examples

In the following examples, you will learn how to check if a specific value is present in a given range.

1. Check if 7 is in the range 4..9

In the following program, we take an integer range 4..9, and check if the value 7 is in this range.

Kotlin Program

fun main() {
    val myRange = 4..9
    val value = 7
    if ( myRange.contains(value) ) {
        println("$value is present in the range.")
    } else {
        println("$value is not present in the range.")
    }
}

Output

7 is present in the range.

2. Check if 3 is in the range 4..9

In the following program, we take an integer range 4..9, and check if the value 3 is in this range.

Kotlin Program

fun main() {
    val myRange = 4..9
    val value = 3
    if ( myRange.contains(value) ) {
        println("$value is present in the range.")
    } else {
        println("$value is not present in the range.")
    }
}

Output

3 is not present in the range.