我怎么能在Kotlin有一个复合键?
在Python中,我可以有复杂的字典键,例如:
d = {} d[(1, 2)] = 3 print d[(1, 2)] # prints 3
我怎样才能在Kotlin中声明和填充这样一个Map?
编辑:我试图宣布这样的地图,但我不知道如何填充它:
val my_map = HashMap<Pair, Int>()
这很简单,你首先创建你的字典,然后插入键和值:
val (a, b):Pair = Pair(1, "x") val map: HashMap, Int> = hashMapOf((a, b) to 1) map[Pair(2, "y")] = 3
等等 :)
在Kotlin中,与Python不同,没有元组数据types。 对于二元组,有一个Pair类。 对于更大的架构,你应该使用数据类。
val map: HashMap, Int> = hashMapOf(Pair(1, 2) to 3) val nullable: Int? = map[Pair(1, 2)] val notNullable = map.getValue(Pair(1, 2))