Reputation: 1376
I know how to check a string is in another string like this code.
when (myString) {
in "FirstString" -> {
// some stuff
}
in "SecondString" -> {
// some stuff
}
else -> {
// some stuff
}
}
in
keyword under the hood calls this method CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false)
the question is this :
is there any way that in this case i can set ignoreCase = true
?
Upvotes: 1
Views: 1179
Reputation: 23105
You can declare an ad-hoc local operator function contains
for strings before when
:
fun main() {
operator fun String.contains(other: String): Boolean = this.contains(other, ignoreCase = true)
when(myString) {
in "firstString" -> ...
}
}
This way that function will be invoked for in
operator instead of the one declared in the standard library because it's located in the closer scope.
Note, however, that this trick works only if the original contains
function is an extension. If it's a member function, it cannot be overridden with an extension.
Upvotes: 4
Reputation: 1327
You can use toLowerCase() function here :
when (myString.toLowerCase()) {
in "firststring" -> {
// some stuff
}
in "secondstring" -> {
// some stuff
}
else -> {
// some stuff
}
}
For the cases of when
, if they're variables toLowerCase()
needs to be called on each of them. But, if they're constants, simple using lower case strings will work - "firststring"
, "secondstring"
Upvotes: 0