Check if value is not equal in when()-statement

Viewed 283

Is it possible to test a String for not being equal in a when-statement?

This is of course perfectly possible with a simpel if statement:

val storedValue = sharedPreferences.getString(identifier, NOT_SET)
if (storedValue != NOT_SET) {
    super.setValue(storedValue)
}

However, I like how storedValue is scoped inside of the when-statement in this snippet:

when (val storedValue = sharedPreferences.getString(identifier, NOT_SET)) {
    NOT_SET -> {}
    else -> super.setValue(storedValue)
}

The downfall is the empty code block for the NOT_SET entry. Is it possible to combine these two?

I'd like to scope storedValue and get rid of empty code blocks. The result would be comparable to:

when (val storedValue = sharedPreferences.getString(identifier, NOT_SET)) {
    !NOT_SET -> super.setValue(storedValue)
}

Since SharedPreferences is part of the Android framework, this would another solution:

if (sharedPreferences.contains(identifier)) {
    super.setValue(sharedPreferences.getString(identifier, null))
}

However, the goal of my question is deeper understanding of the possibilities of Kotlin, for the sake of learning.

1 Answers

As mentioned in the comments, negation is not directly supported like this in when statements (yet) even in Kotlin.

The most idiomatic way at the moment most probably is like:

val storedValue = sharedPreferences.getString(identifier, NOT_SET)
when {
    storedValue != "NOT_SET" -> super.setValue(storedValue)
}

Another working variant utilizing !in in when could be for example:

when (val storedValue = sharedPreferences.getString(identifier, NOT_SET)) {
     !in setOf("NOT_SET") -> super.setValue(storedValue)
}

And as both != and!in will compare case sensitively, so would make sense to get the string like sharedPreferences.getString(identifier, NOT_SET).toUpperCase(), or use equalsIgnoreCase in the first variant.

Related