https://kotlinlang.org logo
#announcements
Title
# announcements
u

Uziel Sulkies

09/18/2019, 7:14 PM
Is there a simple functional way to receive a non-nullable values map?
s

Shawn

09/18/2019, 7:16 PM
I don’t think
filterNot
will do what you want it to
compiler can’t smartcast to non-null
also, you may want to project
V
as
V : Any
s

streetsofboston

09/18/2019, 7:16 PM
No short way, bu maybe like this:
this.filterNot { it.value == null }.map { it as Entry<K,V> }
(not sure if
Entry
is the correct name)
^^^ I’m not even sure that will work….(don’t have IDE in front of me now :-)
This will work, but it will be an unsafe cast 🙂 :
this.filterNot { it.value == null } as Map<K,V>
k

Kroppeb

09/18/2019, 7:20 PM
Just put it into an extension function and call it a day
u

Uziel Sulkies

09/18/2019, 7:23 PM
It is an extension function we're trying to write. It is possible to do it this way. But is there a shorter way?
s

streetsofboston

09/18/2019, 7:25 PM
I think just an unsafe cast would suffice…
Copy code
fun <K, V : Any> Map<K,V?>.filterNotNull(): Map<K,V> = 
    filter { it.value != null } as Map<K,V>
s

Shawn

09/18/2019, 7:43 PM
I mean, no, not just
mapNotNull
you’d need something a little more involved
Copy code
fun <K : Any, V : Any> Map<K, V?>.filterNullValues(): Map<K, V> {
  return mapNotNull { it.value?.let { value -> it.key to value } }.toMap()
}
since
mapNotNull
returns
List<R>
and not a
Map<K, V>
s

Shawn A

09/18/2019, 7:47 PM
Sorry, yes that is what I was getting it. Should have provided an example thanks 🙂
s

Shawn

09/18/2019, 7:48 PM
my point really being that going the
mapNotNull
route involves different tradeoffs, mostly just more iteration over your collection
2 Views