Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method hashMapOf() in Kotlin

Can anybody please give me Concrete example of hashMapOf() method and when should I use it?

If i do something like this:

val map2 : HashMap<String, String>  = hashMapOf()
    map2["ok"] = "yes"

It means to initialize map2 property I can use it.

But like other method in Kotlin for example:

val arr = arrayListOf<String>("1", "2", "3")

Is there any way I can use this method like above?

like image 295
TapanHP Avatar asked Jul 04 '17 11:07

TapanHP


People also ask

How do you use a Hashtable in Kotlin?

Kotlin Hash Table based implementation of the MutableMap interface. It stores the data in the form of key and value pair. Map keys are unique and the map holds only one value for each key. It is represented as HashMap<key, value> or HashMap<K, V>.


2 Answers

It's simple:

val map = hashMapOf("ok" to "yes", "cancel" to "no")

print(map) // >>> {ok=yes, cancel=no}

Method hashMapOf returns java.util.HashMap instance with the specified key-value pairs.

Under the hood:

/**
 * Creates a tuple of type [Pair] from this and [that].
 *
 * This can be useful for creating [Map] literals with less noise, for example:
 * @sample samples.collections.Maps.Instantiation.mapFromPairs
 */
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
like image 161
Alexander Romanov Avatar answered Sep 21 '22 18:09

Alexander Romanov


Yes, you can. First example from kotlinlang.org:

val map: HashMap<Int, String> = hashMapOf(1 to "x", 2 to "y", -1 to "zz")
println(map) // {-1=zz, 1=x, 2=y}
like image 21
Muchomor Avatar answered Sep 20 '22 18:09

Muchomor