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