有一个 map 被传入数据的情况,例如
Map<Pair<Int, Int>), String>
Pair<Int, Int>) // zero based star index, inclusive end index
to
displayString
在执行此过程时,需要为当前位置选择正确的 displayString,例如
var index = 0
for (data in dataList) {
/*
if the current index is within one of the pair<int, int>
then use the mapped displayString
*/
index++
}
在 kotlin 中最好的方法是什么?
最佳答案
不确定这是否是您的意思,但可能是这样的:
var index = 0
for (data in dataList) {
/*
if the current index is within one of the pair<int, int>
then use the mapped displayString
*/
val currentPair = data.key
if ((currentPair.first .. currentPair.second).contains(index)) {
// do something
}
index++
}
虽然如果你的意思是你想要一个 getter 从包含 int 的 map 中获取第一对,也许你想要这样的东西:
fun getByIndex(dataList: Map<Pair<Int,Int>, String>, index: Int): String? {
return dataList.firstOrNull {
(it.key.first .. it.key.second).contains(index)
}
}
使用
until
而不是 ..
具有唯一的结束索引
关于kotlin,如何检查索引是否在范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60377945/