if you really want to ensure the return type can y...
# announcements
c
if you really want to ensure the return type can you use
filterTo
?
👆 1
d
Yes, and you should! This is exactly the thing for this use case.
a
I just tried that hahahah! The problem is, that
filterTo
requires a mutable map, of course
c
uh, is
HashMap
not mutable?
a
Now I’m wishing for a
.filterToType<HashMap<K,V>
or something….
d
That cannot be reasonably implemented without reflection, which is slow, unreliable and ugly.
And that filterToType would still return a mutable map.
All that
filter
does, by the way, is call
filterTo
with a
LinkedHashMap
. So if you do
val filtered: Map<K, V> = filterTo(HashMap()) { }
you have the same effect.
c
you said you wanted to ensure the return type as a
HashMap
using filterTo does that. if you really need you can cast it, although IMO you shouldn't need to know the concrete type in most scenarios
d
Don't cast the result of
filter
! That is not guaranteed to work and might crash with a newer version of Kotlin.
c
you can cast the return of
filterTo
not
filter
nvm shouldn't be necessary
d
You don't need to cast the result of
filterTo
.
Yeah, it returns what you pass in.