Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement Hashmap with different value types in Kotlin

Tags:

hashmap

kotlin

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?

like image 658
Jan Vladimir Mostert Avatar asked May 26 '16 09:05

Jan Vladimir Mostert


Video Answer


2 Answers

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)
like image 83
hotkey Avatar answered Oct 23 '22 13:10

hotkey


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.

like image 40
Pranay Bhalerao Avatar answered Oct 23 '22 12:10

Pranay Bhalerao