This article explores different ways to compare two strings for equality in Kotlin.

1. Equal-to operator (==) operation

In Kotlin, the structural equality is checked by the == operator and its negated counterpart !=. The expression a == b is translated to a?.equals(b) ?: (b === null).

Download Code

 
Note that === should not be used for string equality as it will check for referential equality, i.e., a === b evaluates to true if and only if a and b point to the same object.

2. Using equals() function

Alternatively, you can use the equals() function, which compares the actual contents of a string with another string and returns true if and only if they are equal. Here is an example for matching the two strings using the equals() function.

Download Code

 
To perform a comparison with case ignored, pass true as a second parameter to the equals() function.

Download Code

3. Using compareTo() function

The compareTo() function compares two strings lexicographically, optionally ignoring case. It returns 0 if the string is equal to the argument. Otherwise, it returns the difference between the two character values present at the first non-matching index. The following code example demonstrates the invocation of the compareTo() function:

Download Code

That’s all about comparing two strings for equality in Kotlin.