方法hashMapOf()在Kotlin中
任何人都可以给我一个hashMapOf()
方法的具体例子,我应该什么时候使用它?
如果我做这样的事情:
val map2 : HashMap<String, String> = hashMapOf() map2["ok"] = "yes"
这意味着我可以使用它来初始化map2属性。
但是像Kotlin中的其他方法一样:
val arr = arrayListOf<String>("1", "2", "3")
有什么办法可以像上面那样使用这个方法吗?
这很简单:
val map = hashMapOf("ok" to "yes", "cancel" to "no") print(map) // >>> {ok=yes, cancel=no}
方法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)
是的你可以。 来自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}