Implement a hashmap with different types of values ​​in Kotlin

Is it possible to have a hashmap in Kotlin that accepts different types of values?

I 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 this gives me a type mismatch (apparantly "John", 1and trueare not objects)

In Java, you can get around this by creating types new String("John"), new Integer(1), Boolean.TRUE, I tried the equivalent in Kotlin, but still get the error type mismatch.

context.put("tf", Boolean(true))

Any ideas?

+4
source share
1 answer

In Kotlin Any, this is a supertype of all other types, and you should replace it with Java Object:

val context = HashMap<String, Any>()
context.put("world", "John")
context.put("count", 1)
context.put("tf", true)
+14
source

All Articles