The hashMapOf () method in Kotlin
Can someone please give me a specific example of a method hashMapOf()
and when should I use it?
If I do something like this:
val map2 : HashMap<String, String> = hashMapOf()
map2["ok"] = "yes"
This means initializing the map2 property that I can use.
But like other methods in Kotlin, for example:
val arr = arrayListOf<String>("1", "2", "3")
Can this method be used as described above?
+3
source to share
2 answers
It's simple:
val map = hashMapOf("ok" to "yes", "cancel" to "no")
print(map) // >>> {ok=yes, cancel=no}
The method hashMapOf
returns an instance java.util.HashMap
with the specified key-value pairs.
/**
* 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)
+8
source to share
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}
+1
source to share