Kotlin 有 Map 文字语法吗?

问题描述 投票:0回答:2

在 JavaScript 中:

{foo: bar, biz: qux}

红宝石:

{foo => bar, biz => qux}

在爪哇中:

HashMap<K, V> map = new HashMap<>();
map.put(foo, bar);
map.put(biz, qux);

Kotlin 肯定能比 Java 做得更好吗?

dictionary kotlin literals
2个回答
119
投票

你可以这样做:

val map = hashMapOf(
  "John" to "Doe",
  "Jane" to "Smith"
)

这里,

to
是一个中缀函数,它创建一个
Pair

或者,更抽象:使用

mapOf()
就像

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

(在 kotlinlang 上找到)


18
投票

有人建议将它们添加到语言中:

KT-43871:集合文字 (以前位于 Kotlin/KEEP #112:集合文字

如果发生这种情况,您所询问的语法可能如下:

val map = ["a" : 1, "b" : 2, "c" : 3]
© www.soinside.com 2019 - 2024. All rights reserved.