Kotlin Equal-to

Kotlin Equal-to Operator

Kotlin Equal-to Operator returns true if left operand is equal to right operand, or else it returns false.

Syntax

The syntax to use Equal-to operator is

value1 == value2

where

  • value1 is left operand
  • == is the symbol used for Equal-to operator
  • value2 is right operand

Return value

The above expression returns a boolean value of true if both the values are equal, or false otherwise.

Examples

Check if two given numbers are equal

In the following program, consider that we are given two values in variables: n1, and n2. We shall check if values in n1 and n2 are equal using Equal-to operator.

Kotlin Program

fun main() {
    val n1 = 4
    val n2 = 4

    if (n1 == n2) {
        println("The two numbers are equal.")
    } else {
        println("The two numbers are not equal.")
    }
}

Output

The two numbers are equal.

Since the two given numbers are equal, n1 == n2 returned true, and the if-block is run.

Check if two given strings are equal

In the following program, consider that we are given two string values in variables: str1, and str2. We shall check if values in str1 and str2 are equal using Equal-to operator.

Kotlin Program

fun main() {
    val str1 = "apple"
    val str2 = "banana"

    if (str1 == str2) {
        println("The two strings are equal.")
    } else {
        println("The two strings are not equal.")
    }
}

Output

The two strings are not equal.

Since the two given strings are not equal, n1 == n2 returned false, and the else-block is run.