【问题标题】:Method hashMapOf() in KotlinKotlin 中的方法 hashMapOf()
【发布时间】:2017-12-07 20:52:49
【问题描述】:

谁能给我hashMapOf()方法的具体例子,我应该什么时候使用它?

如果我这样做:

val map2 : HashMap<String, String>  = hashMapOf()
    map2["ok"] = "yes"

表示初始化ma​​p2属性我可以使用。

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

val arr = arrayListOf<String>("1", "2", "3")

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

【问题讨论】:

    标签: android hashmap kotlin


    【解决方案1】:

    很简单:

    val map = hashMapOf("ok" to "yes", "cancel" to "no")
    
    print(map) // >>> {ok=yes, cancel=no}
    

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

    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)
    

    【讨论】:

      【解决方案2】:

      是的,你可以。来自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}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-15
        • 1970-01-01
        • 2018-04-23
        • 2018-02-27
        • 1970-01-01
        • 2022-07-22
        • 2016-09-28
        • 2015-03-28
        相关资源
        最近更新 更多