Kotlin String.equals()

Kotlin String.equals() Tutorial

The String.equals() function in Kotlin is used to check if two strings are equal. It returns true if the strings have the same content, and false otherwise.

This tutorial will explore the syntax of the String.equals() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the String.equals() function is as follows:

fun String.equals(other: Any?): Boolean

where

ParameterDescription
otherThe object to compare with the current string.
Parameters of String.equals() function

Examples for String.equals() function

1. Comparing Equal Strings

In this example, we take two strings in string1 and string2, and check if the values in these strings are equal using String.equals() function.

Kotlin Program

fun main() {
    val string1 = "apple"
    val string2 = "apple"

    // Using equals() to check if two strings are equal
    if (string1.equals(string2)) {
        println("The two strings are equal.")
    } else {
        println("The two strings are not equal.")
    }
}

Output

The two strings are equal.

Since the two strings are equal, string1.equals(string2) returns true and the if-block in if else statement executes.

2. Comparing Different Strings

Now, let us take different string values in string1 and string2, and run the program.

Kotlin Program

fun main() {
    val string1 = "apple"
    val string2 = "banana"

    // Using equals() to check if two strings are equal
    if (string1.equals(string2)) {
        println("The two strings are equal.")
    } else {
        println("The two strings are not equal.")
    }
}

Output

The two strings are not equal.

Since the two strings are not equal, string1.equals(string2) returns false and the else-block in if else statement executes.

Summary

In this tutorial, we’ve covered the String.equals() function in Kotlin, its syntax, and how to use it to check if two strings are equal.