Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Kotlin have a syntax for Map literals?

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?

like image 773
Thomas Avatar asked Feb 10 '17 13:02

Thomas


People also ask

How do you get a map value from Kotlin?

For retrieving a value from a map, you must provide its key as an argument of the get() function. The shorthand [key] syntax is also supported. If the given key is not found, it returns null .

How does map function work in Kotlin?

The basic mapping function is map() . It applies the given lambda function to each subsequent element and returns the list of the lambda results. The order of results is the same as the original order of elements. To apply a transformation that additionally uses the element index as an argument, use mapIndexed() .

Is map immutable in Kotlin?

Kotlin Map : mapOf() Kotlin distinguishes between immutable and mutable maps. Immutable maps created with mapOf() means these are read-only and mutable maps created with mutableMapOf() means we can perform read and write both. The first value of the pair is the key and the second is the value of the corresponding key.


1 Answers

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 )

like image 142
GhostCat Avatar answered Sep 24 '22 01:09

GhostCat