Is it possible to have a hashmap in Kotlin that takes different value types?
I've tried this:
val template = "Hello {{world}} - {{count}} - {{tf}}"
val context = HashMap<String, Object>()
context.put("world", "John")
context.put("count", 1)
context.put("tf", true)
... but that gives me a type mismatch (apparantly "John"
, 1
and true
are not Objects)
In Java you can get around this by creating types new String("John")
, new Integer(1)
, Boolean.TRUE
, I've tried the equivalent in Kotlin, but still getting the type mismatch error.
context.put("tf", Boolean(true))
Any ideas?
In Kotlin, Any
is the supertype of all the other types, and you should replace Java Object
with it:
val context = HashMap<String, Any>()
context.put("world", "John")
context.put("count", 1)
context.put("tf", true)
For new visitors,It can also be done with this
val a= hashMapOf<Any,Any>( 1 to Exception(), 2 to Throwable(), Object() to 33)
Where both keys and values can be of any type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With