在Kotlin中使用不同的值类型实现哈希表

是否有可能在Kotlin有一个HashMap,采取不同的值类型?

我试过这个:

val template = "Hello {{world}} - {{count}} - {{tf}}" val context = HashMap<String, Object>() context.put("world", "John") context.put("count", 1) context.put("tf", true) 

…但这给了我一个类型不匹配(显然是"John"1true的不是对象)

在Java中,你可以通过创建类型new String("John")new Integer(1)Boolean.TRUE ,我试过了Kotlin中的等价物,但仍然得到了类型不匹配的错误。

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

有任何想法吗?

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

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