ribesg
04/01/2019, 2:11 PMMap<String, String?>
as parameter of a function taking Map<Any?, *>
? I assume I can safely do an unchecked cast here, but I wonder why I need it at allstreetsofboston
04/01/2019, 2:14 PMMap<K, out V>
.
The key type is invariant…karelpeeters
04/01/2019, 2:15 PMkarelpeeters
04/01/2019, 2:15 PMThe map is invariant on its key type, as it can accept key as a parameter (of containsKey for example) and return it in keys set.
streetsofboston
04/01/2019, 2:15 PMMap<out Any?, *>
, it will workribesg
04/01/2019, 2:17 PMArtglorin
04/01/2019, 2:18 PMsource as Map<Any?, *>
ribesg
04/01/2019, 2:18 PMstreetsofboston
04/01/2019, 2:19 PMAn unchecked cast would still work, right?Yep, but it may not be safe, depending on your code (ie the compiler cannot guarantee there won’t be any classcast-exceptions) in your code when dealing with your map.
karelpeeters
04/01/2019, 2:20 PMclass MyMap: Map<String, Int> {
override fun containsKey(str: String) = ...
//...
}
ribesg
04/01/2019, 2:21 PMkarelpeeters
04/01/2019, 2:21 PMMap<Any, Int>
and call containsKey(5)
.ribesg
04/01/2019, 2:21 PMribesg
04/01/2019, 2:24 PMval wrongType: Map<String, String?>
val rightType: Map<Any?, *> = HashMap(wrongType)
ribesg
04/01/2019, 2:26 PMHashMap(wrongType)
as parameter directly and I have no warning, it’s also shorter than the castkarelpeeters
04/01/2019, 2:27 PMribesg
04/01/2019, 2:27 PMLinkedHashMap
has more chances to be closer to the original map than HashMap
, so I’ll use that insteadkarelpeeters
04/01/2019, 2:29 PM.toMap()
preserves iteration order too.Artglorin
04/01/2019, 2:33 PMkarelpeeters
04/01/2019, 2:34 PMribesg
04/01/2019, 3:09 PMMap<String, String?>
that I have in the first place, so what @karelpeeters demonstrated could happenilya.gorbunov
04/01/2019, 5:03 PMWill error if you cast it to@karelpeeters it won't, it just returns false: https://pl.kotl.in/S1LBE6kKEand callMap<Any, Int>
.containsKey(5)
karelpeeters
04/01/2019, 5:05 PMilya.gorbunov
04/01/2019, 5:06 PMribesg
04/02/2019, 7:48 AMmyMethod(LinkedHashMap(myMap))
is cleaner than myMethod(myMap as Map<Any?, *>)
anyway. And the second option requires a warning suppression.karelpeeters
04/02/2019, 3:23 PMilya.gorbunov
04/02/2019, 4:17 PM