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?
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 .
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() .
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.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With