在Kotlin中使用不同的值类型实现Hashmap

Jan*_*ert 13 hashmap kotlin

是否有可能在Kotlin中使用不同值类型的哈希映射?

我试过这个:

val template = "Hello {{world}} - {{count}} - {{tf}}"

val context = HashMap<String, Object>()
context.put("world", "John")
context.put("count", 1)
context.put("tf", true)
Run Code Online (Sandbox Code Playgroud)

...但是这给了我一个类型不匹配(apparantly "John",1true不是物)

在Java中,你可以通过创建类型的解决这个问题new String("John"),new Integer(1),Boolean.TRUE,我已经试过在科特林等价,但仍然得到类型不匹配错误.

context.put("tf", Boolean(true))
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

hot*_*key 42

在Kotlin中,Any是所有其他类型的超类型,你应该Object用它替换Java :

val context = HashMap<String, Any>()
context.put("world", "John")
context.put("count", 1)
context.put("tf", true)
Run Code Online (Sandbox Code Playgroud)


小智 5

对于新访客来说,也可以用这个来完成

val a= hashMapOf<Any,Any>( 1 to Exception(), 2 to Throwable(), Object() to 33)
Run Code Online (Sandbox Code Playgroud)

其中键和值都可以是任何类型。