在Kotlin中实现具有不同值类型的Hashmap

Implement Hashmap with different value types in Kotlin

在Kotlin中是否有一个哈希表可以采用不同的值类型?

我已经尝试过:

1
2
3
4
5
6
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中尝试了等效方法,但仍然遇到类型不匹配错误。

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

有什么想法吗?


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

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

对于新访客,也可以使用此

1
val a= hashMapOf<Any,Any>( 1 to Exception(), 2 to Throwable(), Object() to 33)

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