if I have a `Map<String, Thing?>` is there a...
# getting-started
j
if I have a
Map<String, Thing?>
is there an equivalent of
Iterable#filterNoNull()
that will give me a
Map<String,Thing>
for all non-null values?
s
oh god
how do you even have a
Map<String, V?>
sounds like a nightmare to work with
j
mapOf("paramString" to nullableFunction(nullableParameter))
-- yup its ugly
s
if you want to filter out the null mappings eventually, why not perform your filter step earlier?
s
instead of using
null
, could you wrap that failure in a typesafe class?
s
first thought might be to assemble a list of pairs, filterNotNull on the values, and then call toMap() on the resulting
List<Pair<String, V>>
serisium’s suggestion is also a good option if you have the ability to do so in this situation
j
cool, thanks, i'll see what i can wrangle together
s
something like
Copy code
sealed class Thing {
  class Success: Thing()
  class Failure: Thing()
}

val map = mapOf("paramString" to NullableFunction(nullableParameter) ?: Thing.Failure())

val filteredMap = map.filter { k, v -> v is Thing.Success }
j
yeah that could work. what I'm trying to do is have an API layer that has very explicit parameters bridging to an existing more generic implementation that accepts named filters: apiMethod(field1: Filter?, field2: Filter?, field3: Filter?) that internally calls impl(mapOf("field1" to field1, "field2" to field2, "field3" to field3)) --is there a better approach to this?
in the meantime changing nullableFunction to return a
Pair<String,Filter>
and then doing
listOfNotNull(nullableFunction("field1",field1), ....).associate {it.first to it.second }
seems to get what I want. thanks for the help
a
@Joe are you calling an api or are you creating an api?
j
Creating one