Reputation: 11389
Like many other programming languages, Kotlin provides checks like isNullOrEmpty, which allows simply checking variables like myString.isNullOrEmpty()
.
Is there a way to combine such a check with a when expression? By default, the expression only allows explicit strings. Is something like this possible?:
when (myString) {
"1" -> print("1")
"2" -> print("1")
myString.isNullOrEmpty() -> print("null or empty") //This is what I am looking for
else -> print("None of them")
}
Upvotes: 1
Views: 3164
Reputation: 27226
I hadn't tested this, but then realized the logic is inverted :)
So you want to return null when it's NOT null or Empty (it sounds confusing) but this is because you want to return the exact string (source) if it's null or empty, so the when statement matches (remember you're comparing strings) and so it goes into the "is null or empty" branch.
Here's an updated version:
fun CharSequence?.nullOrEmpty(): CharSequence? =
if (isNullOrBlank().not()) null else this
A bit confusing, so you're gonna have to find a nicer name :)
Alternatively, you can make a regular function like:
fun nullOrEmpty(source: String?): String? =
if (source.isNullOrEmpty().not()) null else source
And then call it like:
when (source) {
"1" -> print("1")
"2" -> print("2")
nullOrEmpty(source) -> print("It's null or empty")
else -> print("none")
}
Again, the naming should be improved (good luck, naming is hard!) :)
Consider isNullOrBlank()
too, since that one will prevent strings like " "
too, whereas empty only checks length == 0
Vadik's answer is correct; if you want a "function", you can extend one:
fun irrelevant(source: String?) {
when (source) {
"1" -> print("1")
"2" -> print("1")
source.nullOrEmpty() -> print("null or empty")
else -> print("none")
}
}
fun CharSequence?.nullOrEmpty(): CharSequence? = if (isNullOrEmpty()) null else this
Upvotes: 2
Reputation: 4602
You can eliminate argument of when
like this:
when {
myString == "1" -> print("1")
myString == "2" -> print("2")
myString.isNullOrEmpty() -> print("null or empty")
else -> print("None of them")
}
Or explicitly say "null or empty string":
when (myString) {
"1" -> print("1")
"2" -> print("2")
null, "" -> print("null or empty")
else -> print("None of them")
}
Upvotes: 5