1. Overview
In this tutorial, we’ll discuss different ways of comparing Strings in Kotlin.
2. Comparison Operators
Let’s start with the “==” operator. This operator can be used to check if the 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, if we 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.
When we initialize string values using quotes, they point to the same object. However, if we build a string separately, the variable will point to a separate object:
val copyOfFirst = buildString { "kotlin" } assertTrue { first === second } assertFalse { first === copyOfFirst }
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 has a compareTo method which can be used to compare the order of the two strings. Like 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.