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)

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

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?

推荐答案

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)

Kotlin相关问答推荐

如何确保Kotlin子类已完成初始化?

编译后的JavaFX应用程序立即以静默方式崩溃

如何使用 Kotlin Maven 更改 Minecraft 插件中的 Shulker GUI 标题

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

TzdbZoneRulesProvider 在 java.time 中不工作

如何将光标从一个文本字段传递到 Jetpack Compose 中的其他文本字段?

验证构造函数中的值组合

Jetpack Compose:当状态从另一个活动改变时强制重组

Kotlin:伴随对象内的函数扩展

如何在 Kotlin 中使用具有继承的泛型

为什么我们在 kotlin 中需要 noinline?

OnClickListener 未在 ConstraintLayout 上触发

Kotlin:内部类如何访问在外部类中声明为参数的变量?

Swift vs Kotlin 在排序数组上的表现

从列表中的每个对象中 Select 属性

Map.mapTo 到另一个map

无法创建类 ViewModel kotlin 的实例

Kotlin:使用自定义设置器时没有lateinit的解决方法?

Kotlin-将UTC转换为当地时间

如何在伴随对象中使用泛型