我在Swift中有一行:
var map: [String:[String]] = [String:[String]]()
map[x]!.append(product)
我很好奇map[x]!.append(product)
的实现意味着什么,另外,Kotlin的适当翻译是什么。
Sam的回答很好,但是我推荐稍微不同的Kotlin语法:
val map = mutableMapOf<String, MutableList<String>>()
map.getValue("x").add("product")
一般来说,我建议不要显式定义类型,而是让它们被推断出来。我也更喜欢使用标准库mutableMapOf()
函数来显式调用HashMap
构造函数。
最后,我建议在访问知道存在的键的映射时使用getValue()
而不是[]!!
。如果您不能100%确定,那么我建议使用空安全访问:
map["x"]?.add("product")
我们先把这一行拆分成几个小部分:
map[x]!.append(product)
默认情况下,哈希映射返回一个可选值,因为它可能包含也可能不包含给定的键。把它想象成类型:
map[x] // Gives us a [String]?
有几种方法可以打开可选的。最不安全,但最简单的方法是使用显式展开(使用!)
map[x]! // Gives us a [String]
要添加到现有数组中,请使用append()方法。要求:
map[x]!.append(product)
将结果添加到字符串数组中。
添加到数组的示例:
var fruitArray = ["Apple", "Banana"]
var newFruit = "Orange"
fruitArray.append(newFruit)
// fruitArray will now be ["Apple", "Banana", "Orange"]
包含要添加到的数组的map示例:
var productMap = ["fruits": ["Apple", "Banana"]]
// productMap["fruits"] is ["Apple", "Banana"]
// This is a new fruit we want to add
var newFruit = "Orange"
// Lets add new fruit to fruits
productMap["fruits"].append(newFruit)
// productMap["fruits"] will now be ["Apple", "Banana", "Orange"]
给定代码的Kotlin等价:
val map:HashMap<String,MutableList<String>> = HashMap<String,MutableList<String>>();
map[x]!!.add(product);