kotlin,如何检查索引是否在范围内

标签 kotlin

有一个 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/

相关文章:

wildcard - Kotlin - "Don' t care”数据类脱糖

android - 如何在 kotlin 中使用 fragment

java - Kotlin 的 Flyway 迁移失败

android - UI 线程上的单元测试协程

java - Kotlin lateinit 对应java

android - 为什么在使用AutoFactory时在Kotlin中得到NonExistentClass?

android - NavGraphBuilder 中的可组合项重复 3 次或更多次

kotlin - 使用Kotlin契约在Iterable函数谓词中强制转换类型

function - 如何使用这个函数 Map.getValue( thisRef : Any? , property: KProperty<*>)

android - 编译器发生异常 (1.8.0_301)