Why can’t I pass a value of type `Map<String, S...
# announcements
r
Why can’t I pass a value of type
Map<String, String?>
for a parameter requiring type
Map<Any?, *>
?
b
String extends Any whereas String? extends Any?
In short Any does NOT extend Any?
r
I can’t pass
Map<String?, String?>
either
b
Ah
Your parameter def needs to be
Map<out Any?, *>
☝️ 1
r
Well it’s not my function
b
Otherwise it'll require you to cast to Any, rather than allowing extensions
Then cast your map to required type
r
Yeah a forced cast should not cause any problem in this specific case
The function I called is defined as
Copy code
@kotlinx.cinterop.ObjCMethod public open external fun setMetadata(metadata: kotlin.collections.Map<kotlin.Any?, *>): kotlin.Unit
b
It's an open function. I'd override it with modified def
See if the compiler complains
t
generics are invariant i.e. String
is
Any but List<String>
!is
List<Any>
r
I’m calling this only once so I’ll go with a forced cast
s
@thana A List<String> is a List<Any>, since list is defined as
List<out T>
5
But for a Map, the key is an invariant, not a covariant:
Map<K, out V>
t
Oh yes, you are right i forgot about declaration-site varrance in kotlin and just copied the standard java example over
s
(if it weren’t for the
keys
and
entries
properties, Map could have been `Map<in K, out V>`….)
☝️ 1
l
Answering the initial question: Because if you pass it to
Map<Any?, *>
, you would then be able to put anything in the map, be it mutable under the hood.