android - Swift 在 Kotlin 中的 replaceSubrange

标签 android kotlin

什么是实现类似 Swift 的优雅方式:

sections.replaceSubrange(sectionIndex ..< (sectionIndex + 1), with: [section])

在 Kotlin 中?

到目前为止我的代码:

var filters = BehaviorRelay.create<List<FilterSection>>()

 fun updateFilters(type: FilterType, filtersArray: List<Filter>, state: SectionState = SectionState.Loaded){
        val sectionIndex = filters.value.indexOfFirst { it.filterType == type }
        val section =  filters.value[sectionIndex].update(state, filtersArray)
        val sections = filters.value
        //here is where I need to replace the elements
        filters.accept(sections)
    }

最佳答案

标准库中没有内置函数。但是,您可以按如下方式定义扩展:

fun <T> List<T>.replaceSubrange(subrange: IntRange, withItems: List<T>): List<T> =
    take(subrange.first) + withItems + drop(subrange.endInclusive + 1)
> listOf(1, 2, 3, 4, 5).replaceSubrange(1..3, listOf(0, 0, 0, 0))
[1, 0, 0, 0, 0, 5]

或者,如果您只需要将子列表插入到列表中:

fun <T> List<T>.insertSubrangeAt(index: IntRange, items: List<T>): List<T> =
    take(atIndex) + items + drop(atIndex)
> listOf(1, 2, 3, 4, 5).insertSubrangeAt(1, listOf(0, 0, 0, 0))
[1, 0, 0, 0, 0, 2, 3, 4, 5]

关于android - Swift 在 Kotlin 中的 replaceSubrange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51860915/

相关文章:

android - 我想使用共享首选项将联系人保存在屏幕上

android - 使用 Intent 打开相机

android - 初始化空字节数组

android - 添加/删除方法在 onCreate 中起作用,但在 onPageSelected 中不起作用

java - android 中的 Calendar 类有什么问题吗?

android - 单击Button时,我希望将Fragment 1布局替换为Fragment 2布局,但抛出该异常:java.lang.NullPointerException

java - 如何在Android中读取相对路径上的Json

android - 使用 Powermock2 和 Kotlin 模拟静态类

Android通知取消回调?

构建 iOS 应用程序时,Kotlin/Native compileKotlinIosX64 任务失败