is there a cleaner way to do this? ```val filtered...
# announcements
n
is there a cleaner way to do this?
Copy code
val filteredMap: Map<String, B> = someMap.filterValues { value -> value is B } as Map<String, B>
because the unchecked cast is marked as warning
n
not sure. I'd probably just make my own
filterValuesInstanceOf
method and suppress it there.
n
Depends what you mean by cleanly
You could just add another step where you do the downcast after filtering
Instead of casting the collection
That's obviously adding work though
You could do it in a single step it looks like using mapNotNullTo, but it's a bit awkward
Another option is to write your own associateNotNull, it's not in the standard library unfortunately. With that function it would be easy
Writing it is also pretty easy
n
i eneded up doing these:
Copy code
inline fun <K, reified RV> Map<K, *>.filterValueIsInstance(): Map<K, RV> {
    @OptIn(ExperimentalStdlibApi::class)
    return buildMap {
        this@filterValueIsInstance.filterValueIsInstanceTo(this)
    }
}

inline fun <reified RK: K, reified RV: V, K, V, C : MutableMap<in RK, in RV>> Map<K, V>.filterIstInstance(destination: C): C {
    for ((key, value) in this) if (key is RK && value is RV) destination.put(key, value)
    return destination
}

inline fun <reified RV: V, K, V, C : MutableMap<K, in RV>> Map<K, *>.filterValueIsInstanceTo(destination: C): C {
    for ((key, value) in this) if (value is RV) destination.put(key, value)
    return destination
}

inline fun <reified RK: K, K, V, C : MutableMap<in RK, V>> Map<*, V>.filterKeyIsInstance(destination: C): C {
    for ((key, value) in this) if (key is RK) destination.put(key, value)
    return destination
}
i guess for completions sake i will add a few more like that
v
One way would be
Copy code
val filteredMap: Map<String, B> = someMap.mapNotNull { (key, value) -> if (value is B) key to value else null }.toMap()