my assumption was that the lambda in getOrElse sho...
# codereview
a
my assumption was that the lambda in getOrElse should need to return Heros object as default value
s
unsure if you’ve realized yet, but this is why
age1
is typed as
Any
instead of
Hero
- you’re supplying an Int as a default for a
get
that returns
Hero?
you’re conflating steps - getting an object out of the map and accessing a property in that property
you’re only doing the former
this is still being statically checked, by the way, but the type system inference sorta relies on you knowing what you’re doing
a
Thanks @Shawn for reply....but getOrElse accepts lambda of type () -> V where V should ideally be match with value type present in Map<K, V>.....so effectively getOrElse should accepts () -> Heros but it is also accepting () -> Int
I am a beginner so I am little bit confused here....but can be trivial question
Can you please direct me to any resource which talks more about this?
s
Basically the short answer is that this is happening due to variance, specifically because the signature of the map interface isn’t
Map<K, V>
, it’s
Map<K, out V>
. When calling
.getOrElse()
with a lambda that returns a type that isn’t
V
or a subtype, the type system infers that you intend to operate on a map where
K
is the same, but
V
is now a supertype of the original map’s
V
, since it’s a covariant type parameter
👍 1
in this case
V
is resolved to be the only thing it can be, which is
Any
if you try calling getOrElse with explicit type parameters like this
Copy code
mapByName.getOrElse<String, Any>("unknown") { 0 }
IntelliJ will gray out the parameters and indicate that they are redundant since this is what the type system has already resolved
you can also see this in action by just assigning the map to a valid supertype
Copy code
val superMap: Map<String, Any> = mapByName
if you explicitly annotate
age1
as
Hero
, or change the invocation to
.getOrDefault<String, Hero>()
then the type checker will raise an error
a
yes that I tried...thanks for the information 🙂
a
thanks...Need to go through it....much to digest