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?
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>.
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)
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}
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