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

cdurham

07/28/2017, 10:52 PM
if you really want to ensure the return type can you use
filterTo
?
👆 1
d

diesieben07

07/28/2017, 10:53 PM
Yes, and you should! This is exactly the thing for this use case.
a

aphex

07/28/2017, 11:01 PM
I just tried that hahahah! The problem is, that
filterTo
requires a mutable map, of course
c

cdurham

07/28/2017, 11:01 PM
uh, is
HashMap
not mutable?
a

aphex

07/28/2017, 11:02 PM
Now I’m wishing for a
.filterToType<HashMap<K,V>
or something….
d

diesieben07

07/28/2017, 11:02 PM
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

cdurham

07/28/2017, 11:05 PM
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

diesieben07

07/28/2017, 11:06 PM
Don't cast the result of
filter
! That is not guaranteed to work and might crash with a newer version of Kotlin.
c

cdurham

07/28/2017, 11:06 PM
you can cast the return of
filterTo
not
filter
nvm shouldn't be necessary
d

diesieben07

07/28/2017, 11:06 PM
You don't need to cast the result of
filterTo
.
Yeah, it returns what you pass in.
3 Views