什么是实现类似 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/