I'm having some trouble with type inference. For e...
# announcements
t
I'm having some trouble with type inference. For example, if I write:
Copy code
val myMap = mapOf("id" to 10, "hash" to 99999L)
I would expect the
id
key to contain an
Int
and the
hash
key to contain a
Long
, but that's not the case--
id
is now mapped to a long! I can fix this by writing
Copy code
val myMap = mapOf("id" to 10 as Int, "hash" to 9999L)
But then IntelliJ tells me that the cast is not needed. Is there a better way?
h
You could make the type of the resulting Map explicit:
Copy code
val myMap = mapOf<String,Number>("id" to 10, "hash" to 99999L)
t
My map will have more than numbers (it's a map-representation of a struct) So I'd use
map<String, Any>
But I find it very odd that Kotlin does this kind of upcasting. 😞
e
it's not casting, it's that integer literals take on the expected type
e.g.
val i: Long = 10
,
val b: Byte = 10
t
Oh I see!
e
so you could also
mapOf("id" to 10.toInt(), "hash" to 9999L)
to force it to be considered as an
Int
literal
(despite looking like a function call,
<literal>.toInt()
etc. are treated like constant literals by the compiler)
t
🤯