实现像Swift一样的优雅方法是什么
sections.replaceSubrange(sectionIndex ..< (sectionIndex + 1), with: [section])
在科特林吗?
到目前为止,我的代码:
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)
}
答案 0 :(得分:4)
标准库中没有内置函数。但是,您可以如下定义扩展名:
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]