https://kotlinlang.org logo
#codereview
Title
# codereview
m

myanmarking

01/28/2022, 7:45 PM
Can any1 help me understand why the built-in type inference for map is not working
val map: Map<String, Data> = ..
val temp = map - 1
public operator fun <K, V> Map<out K, V>.minus(key: K): Map<K, V> =
this.toMutableMap().apply { minusAssign(key) }.optimizeReadOnlyMap()
why am i allowed to do that (temp variable) without the compiler complaining. Clearly there is
out K
there.
i can even do:
temp - context
. It must be some compiler bug i guess
j

Javier

01/28/2022, 7:56 PM
K = String, 1 = Int
m

myanmarking

01/28/2022, 7:56 PM
?
j

Joffrey

01/28/2022, 8:07 PM
You're allowed to do this because
K
is then inferred to
Any
for
temp
. Try to add an explicit type for the
temp
variable, you'll see that trying
Map<String, Data>
shouldn't work.
Clearly there is 
out K
 there.
This is exactly why you can do this. A
Map<String, Data>
conforms to
Map<out Any, Data>
, so you can call the
minus
function with
K=Any
on this
Map<String, Data>
without issues.
2 Views