Kotlin中的方法hashMapOf()

Tap*_*nHP 7 android hashmap kotlin

有人可以给我具体的hashMapOf()方法示例,我应该何时使用它?

如果我做这样的事情:

val map2 : HashMap<String, String>  = hashMapOf()
    map2["ok"] = "yes"
Run Code Online (Sandbox Code Playgroud)

这意味着初始化map2属性我可以使用它.

但是像Kotlin中的其他方法一样:

val arr = arrayListOf<String>("1", "2", "3")
Run Code Online (Sandbox Code Playgroud)

我有什么方法可以像上面那样使用这种方法吗?

Ale*_*nov 14

这很简单:

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

print(map) // >>> {ok=yes, cancel=no}
Run Code Online (Sandbox Code Playgroud)

Method hashMapOf返回java.util.HashMap具有指定键值对的实例.

引擎盖下:

/**
 * 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)
Run Code Online (Sandbox Code Playgroud)