Does Kotlin have a syntax for Map literals?

Thomas picture Thomas · Feb 10, 2017 · Viewed 16.7k times · Source

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?

Answer

GhostCat picture GhostCat · Feb 10, 2017

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 )