Kotlin equivalent of Java's equalsIgnoreCase
AndroidKotlinAndroid Problem Overview
What is the equivalent of Java equalsIgnoreCase
in Kotlin to compare String
values?
I have used equals
but it's not case insensitive.
Android Solutions
Solution 1 - Android
You can use equals
but specify ignoreCase
parameter:
"example".equals("EXAMPLE", ignoreCase = true)
Solution 2 - Android
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 > } > }
Solution 3 - Android
@hluhovskyi's answer is correct, however to use it on EditText
or TextView
, use following -
etPassword.text.toString().equals(etConfirmPassword.text.toString(), ignoreCase = true)
Solution 4 - Android
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)
Solution 5 - Android
In my case,
string1.contains(string2, ignoreCase = true)
This worked for me. Becase I'm using like a search function here.