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