Does Kotlin have a syntax for Map literals?

DictionaryKotlinLiterals

Dictionary Problem Overview


In JavaScript: {foo: bar, biz: qux}.

In Ruby: {foo => bar, biz => qux}.

In Java:

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

Surely Kotlin can do better than Java?

Dictionary Solutions


Solution 1 - Dictionary

You can do:

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

Here, to is an infix function that creates a Pair.

Or, more abstract: use mapOf() like

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

( found on kotlinlang )

Solution 2 - Dictionary

There is a proposal to add them to the language:

Kotlin/KEEP: Collection Literals

If this goes through, the syntax might be like:

val map = ["a" : 1, "b" : 2, "c" : 3]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThomasView Question on Stackoverflow
Solution 1 - DictionaryGhostCatView Answer on Stackoverflow
Solution 2 - DictionaryKy.View Answer on Stackoverflow