1. Overview

In this tutorial, we’ll discuss different ways of comparing Strings in Kotlin.

2. Comparison Operators

Let’s start with the “==” operator.

We can use it to check if two strings are structurally equal. It’s the equivalent of using the equals method in Java:

val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first == second }
assertFalse { first == firstCapitalized }

Now, let’s consider the referential equality operator “===”. It returns true if the two variables are pointing to the same object. It’s the equivalent of using == in Java.

Whenever we initialize a new String object using quotes, it’s automatically placed in the string pool. Therefore, two equal strings created that way will always reference the same object:

assertTrue { first === second }

However, if we use a constructor to create a new String, we explicitly tell Kotlin we want a new object. Consequently, a new String will be created and put on the heap:

val third = String("kotlin".toCharArray())
assertTrue { first == third }
assertFalse { first === third }

3. Comparing with equals

The equals method returns the same result as the “==” operator:

assertTrue { first.equals(second) }
assertFalse { first.equals(firstCapitalized) }

When we want to do a case-insensitive comparison, we can use the equals method and pass true for the second optional parameter ignoreCase:

assertTrue { first.equals(firstCapitalized, true) }

4. Comparing with compareTo

Kotlin also has a compareTo method which we can use to compare the order of the two strings. Similarly, as the equals method, the compareTo method also comes with an optional ignoreCase argument:

assertTrue { first.compareTo(second) == 0 }
assertTrue { first.compareTo(firstCapitalized) == 32 }
assertTrue { firstCapitalized.compareTo(first) == -32 }
assertTrue { first.compareTo(firstCapitalized, true) == 0 }

The compareTo method returns zero for equal strings, a positive value if the argument’s ASCII value is smaller, and a negative value if the argument’s ASCII value is greater. In a way, we can read it like we read subtraction.

In the last example, due to the ignoreCase argument, the two strings are considered equal.

5. Conclusion

In this quick article, we saw different ways of comparing strings in Kotlin using some basic examples.

As always, please check out all the code over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.