Compare Strings in Kotlin
To compare strings in Kotlin, use == when you want to check whether two string values contain the same text. Use compareTo() when you want lexical ordering, such as sorting strings or checking whether one string comes before another.
Kotlin string comparison is different from Java in one important way: in Kotlin, == checks structural equality, not reference equality. For strings, this means a == b compares the text content of the two strings. If you specifically want to compare references, Kotlin provides the === operator.
When to Use ==, equals(), compareTo(), and === for Kotlin Strings
The following table gives a quick decision guide for common Kotlin string comparison needs.
| Requirement | Use | What it checks |
|---|---|---|
| Check whether two strings have the same text | == | Structural equality, translated safely to equals() |
| Check text equality with optional case-insensitive comparison | equals(other, ignoreCase = true) | String content, optionally ignoring letter case |
| Order strings lexically | compareTo() | Whether one string is equal to, less than, or greater than another string |
| Check whether two variables refer to the same object | === | Reference equality |
Using “==” Operator
We shall use == operator for comparing two Strings in Kotlin. According to the documentation of Equality in Kotlin, == operator is used for Structural Equality.
a==b is implicitly translated to a?.equals(b) ?: (b === null) by Kotlin language.
Make sure that the two values a and b are of type Strings. Else convert them to Strings before comparison.
The == operator is null-safe. If the left side is not null, Kotlin calls equals(). If the left side is null, the result is true only when the right side is also null.
Example 1 – Compare Strings
In the following example, we will take two strings in a and b variables, and compare them using == operator.
example.kt
/**
* Kotlin example to compare if two strings are equal
*/
fun main(args: Array<String>) {
var a: String = "kotlin is easy"
var b: String = "kotlin is" + " easy"
if(a==b){
println("Strings '$a' and '$b' are equal.")
} else {
println("Strings '$a' and '$b' are not equal.")
}
b = "Kotlin runs on JVM"
if(a==b){
println("Strings '$a' and '$b' are equal.")
} else {
println("Strings '$a' and '$b' are not equal.")
}
}
Output
Strings 'kotlin is easy' and 'kotlin is easy' are equal.
Strings 'kotlin is easy' and 'Kotlin runs on JVM' are not equal.
Case-Insensitive String Equality in Kotlin
The == operator is case-sensitive. For example, "Kotlin" == "kotlin" is false because uppercase K and lowercase k are different characters.
For case-insensitive equality, call equals() with ignoreCase = true.
example.kt
fun main() {
val first = "Kotlin"
val second = "kotlin"
println(first == second)
println(first.equals(second, ignoreCase = true))
}
Output
false
true
This is useful when comparing user input, search keywords, tags, or commands where letter case should not change the result.
Kotlin String == vs === Operator
In Kotlin, == and === do not mean the same thing.
==checks whether two values are structurally equal.===checks whether two references point to the same object.
For most string comparison tasks, use ==. Use === only when reference identity itself is the requirement.
example.kt
fun main() {
val a = String(charArrayOf('h', 'e', 'l', 'l', 'o'))
val b = String(charArrayOf('h', 'e', 'l', 'l', 'o'))
println(a == b)
println(a === b)
}
Output
true
false
Both strings contain the same characters, so == returns true. They are separate objects, so === returns false.
Null-Safe Kotlin String Comparison
Because == is translated into a null-safe equality check, it can compare nullable strings without throwing a null pointer exception.
example.kt
fun main() {
val a: String? = null
val b: String? = "kotlin"
val c: String? = null
println(a == b)
println(a == c)
}
Output
false
true
This makes == the preferred choice for normal equality checks, including nullable string values.
Using compareTo() extension function
Kotlin provides compareTo() extension function to String.
The syntax of compareTo() function is
fun String.compareTo(
other: String,
ignoreCase: Boolean = false
): Int
other: String is mandatory argument.
ignoreCase is optional.
The function returns integer value.
| Return Value | Description |
|---|---|
| 0 | The two strings are equal. |
| negative integer | If the string is less than the other string |
| positive integer | If the string is greater than the other string |
The compareTo() function is useful when equality alone is not enough. For example, sorting names, ordering labels, or checking whether a string comes before another string can use compareTo().
Example 2 – Compare Strings – String.compareTo()
In the following example, we will compare two strings in Kotlin using the function String.compareTo()
example.kt
/**
* Kotlin example to compare two strings
*/
fun main(args: Array<String>) {
var a: String = "apple"
var b: String = "apple"
var result = a.compareTo(b)
if(result==0){
println("Strings '$a' and '$b' are equal.")
} else if(result < 0){
println("'$a' is less than '$b' lexically.")
} else{
println("'$a' is less than '$b' lexically.")
}
b = "banana"
result = a.compareTo(b)
if(result==0){
println("Strings '$a' and '$b' are equal.")
} else if(result < 0){
println("'$a' is less than '$b' lexically.")
} else{
println("'$a' is less than '$b' lexically.")
}
// passing ignoreCase to compareTo
a = "appLE"
b = "aPple"
println("\nIgnoring Case...")
result = a.compareTo(b, true) // ignoreCase = true
if(result==0){
println("Strings '$a' and '$b' are equal.")
} else if(result < 0){
println("'$a' is less than '$b' lexically.")
} else{
println("'$a' is less than '$b' lexically.")
}
}
Output
Strings 'apple' and 'apple' are equal.
'apple' is less than 'banana' lexically.
Ignoring Case...
Strings 'appLE' and 'aPple' are equal.
Note that a positive result from compareTo() means the first string is greater than the other string lexically. A negative result means the first string is less than the other string lexically. The exact integer value should not be used as a business rule; check whether it is less than, equal to, or greater than zero.
Sorting Kotlin Strings with compareTo()
The compareTo() result is also used by sorting functions. The following example sorts a list of strings in natural order and then in case-insensitive order.
example.kt
fun main() {
val names = listOf("banana", "Apple", "cherry", "apple")
println(names.sorted())
println(names.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it }))
}
Output
[Apple, apple, banana, cherry]
[Apple, apple, banana, cherry]
For simple equality checks, sorting is not required. For ordering strings in collections, use sorting functions or compareTo() depending on the problem.
Common Mistakes When Comparing Strings in Kotlin
- Using
===for text comparison: This checks whether both variables refer to the same object. Use==for string content comparison. - Expecting
==to ignore case: It is case-sensitive. Useequals(other, ignoreCase = true)for case-insensitive checks. - Using the exact return value of
compareTo(): Use only the sign of the returned integer: zero, negative, or positive. - Comparing mixed types without conversion: Compare strings with strings. Convert other values explicitly when required.
- Using
compareTo()when only equality is needed: Use==orequals()for clearer equality checks.
Kotlin String Comparison QA Checklist
- Use
==for normal Kotlin string content comparison. - Use
equals(other, ignoreCase = true)when uppercase and lowercase letters should be treated as equal. - Use
compareTo()only when lexical ordering is required. - Use
===only when checking whether two references point to the same object. - Test nullable string inputs when the comparison can receive null values.
Frequently Asked Questions on Kotlin String Comparison
Can I use == to compare strings in Kotlin?
Yes. In Kotlin, == checks structural equality. For strings, it compares the text content, so it is the usual operator for checking whether two strings are equal.
What is the difference between == and === for Kotlin strings?
== checks whether two strings have equal content. === checks whether both variables refer to the same object. For string text comparison, use ==.
How do I compare strings in Kotlin while ignoring case?
Use equals() with ignoreCase = true. For example, first.equals(second, ignoreCase = true) compares two strings without treating uppercase and lowercase versions of the same letter as different.
When should I use compareTo() for Kotlin strings?
Use compareTo() when you need lexical ordering. It returns zero for equal strings, a negative integer when the first string is less than the second string, and a positive integer when the first string is greater than the second string.
Is Kotlin string comparison with == null-safe?
Yes. Kotlin translates a == b into a null-safe equality check. If both nullable strings are null, the result is true. If only one is null, the result is false.
Kotlin String Comparison Summary
In this Kotlin Tutorial – Compare Strings in Kotlin, we have learnt to compare two strings using == Operator and CompareTo() String function, with the help of example programs.
For most Kotlin programs, == is the correct choice for checking whether two strings contain the same text. Use equals() when you need case-insensitive equality, compareTo() when you need lexical ordering, and === only for reference comparison.
TutorialKart.com