https://kotlinlang.org logo
Title
b

bdawg.io

10/26/2017, 11:21 PM
On another topic, Which would you choose? Goal: reassign
filters[property]
if merging two nullable sets yields a non-empty set 1️⃣
val additional: Set<T>? = filterStates[requested]
if (additional is Set<*> && additional.isNotEmpty()) {
    val current: Set<T>? = filters[property]
    if (current is Set<*> && current.isNotEmpty()) {
        filters[property] = current.plus(additional)
    } else {
        filters[property] = additional
    }
}
2️⃣
filters[property].plusMaybe(filterStates[requested.value])?.let {
    filters[property] = it
}

fun <T : Any> Set<T>?.plusMaybe(other: Set<T>?): Set<T>? = (this ?: emptySet()).plus(other ?: emptySet()).takeIf { it.isNotEmpty() }
1️⃣ 2
2️⃣ 1
d

diesieben07

10/26/2017, 11:27 PM
Why so complicated?
val new = (filterStates[requested] ?: emptySet()) + (filters[property] ?: emptySet())
if (new.isNotEmpty()) {
    filters[property] = new
}
3️⃣ 2
b

bdawg.io

10/26/2017, 11:33 PM
Ahh, that does look pleasing. While it does increase the assignments to
filters[property]
it wouldn’t be an issue in the case of a backing field
d

diesieben07

10/26/2017, 11:33 PM
How does it increase the assignments?
b

bdawg.io

10/26/2017, 11:34 PM
Currently, if
filterStates[requested]
yields null, it will short circuit from doing the assignment altogether
d

diesieben07

10/26/2017, 11:35 PM
Ah, true. But that is not in line with the goal you posted 😄
👍 1
b

bdawg.io

10/26/2017, 11:36 PM
Right, which is why I mentioned it wouldn’t be an issue anyways 🙂
@diesieben07 I think I’m going to use that one. Makes the code way more readable
🎉 1