148

What is the equivalent of Java equalsIgnoreCase in Kotlin to compare String values?

I have used equals but it's not case insensitive.

Farwa
  • 6,156
  • 8
  • 31
  • 46

6 Answers6

261

You can use equals but specify ignoreCase parameter:

"example".equals("EXAMPLE", ignoreCase = true)
hluhovskyi
  • 9,556
  • 5
  • 30
  • 42
11

As per the Kotlin Documentation :

fun String?.equals(
    other: String?, 
    ignoreCase: Boolean = false
): Boolean

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/equals.html

For Example:

val name: String = "Hitesh"
when{
name.equals("HITESH", true) -> {
                                // DO SOMETHING
    }
}
Hitesh Dhamshaniya
  • 2,088
  • 2
  • 16
  • 23
5

@hluhovskyi's answer is correct, however to use it on EditText or TextView, use following -

etPassword.text.toString().equals(etConfirmPassword.text.toString(), ignoreCase = true)
Daria Pydorenko
  • 1,754
  • 2
  • 18
  • 45
Rohan Kandwal
  • 9,112
  • 8
  • 74
  • 107
2

In my case,

string1.contains(string2, ignoreCase = true)

This worked for me. Becase I'm using like a search function here.

G Ganesh
  • 103
  • 7
1

You could make an extension method:

    /**
     * Shortcut to compare strings while ignoring case
     */
    fun String.similarTo(aString: String): Boolean {
        return equals(aString,true)
    }

Usage:

   val upperCase = "ϴẞ"
   val lowerCase = "θß"

   if (upperCase.similarTo(lowerCase)) {
      // Do your thing…
   }
Slion
  • 2,558
  • 2
  • 23
  • 27
0

Normally, you don't need to find alternatives since Kotlin reuses existing Java types like String. Actually, these types are mapped to Kotlin internal types. In the case of String it looks like this:

java.lang.String -> kotlin.String

Therefore, the desired method equalsIgnoreCase would only be available if it was also provided in kotlin.String, which isn’t. The Kotlin designers decided to provide a more generic equals function that let's you specify the case insensitivity with a boolean parameter.

You can use the Java String class at any time if that's really necessary (it's not recommended, IntelliJ will complain about this):

("hello" as java.lang.String).equalsIgnoreCase("Hello")

With the help of an extension function, we could even add the functionality to the kotlin.String class:

fun String.equalsIgnoreCase(other: String) = 
    (this as java.lang.String).equalsIgnoreCase(other)
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • 1
    Kotlin has equalIgnoreCase function implemented, but with a little change with its own way i.e. "str1".equal("Str1", true) for ignore case and "str1".equal("Str1", false) for match case. Second argument is optional you can skip it. By default it is false and apply on match case – Abdur Rahman Feb 02 '19 at 09:19