Kotlin:在给定索引后从列表中获取项目的 Idomatic 方法

Kotlin: Idomatic way to get items from list after a given index

假设我有一个包含 30 个项目的列表并且给定索引为 9,我需要获取从索引 10 到 19 开始的项目。

目前正在以 Java 风格进行。

                val newsList: ArrayList<Model> = arrayListOf()

                    // Get all items starting next to the current selected item
                    for (i in (position + 1) until originalList.size) {

                        // Limit the amount of item to avoid any possible OOM
                        if (newsList.size < 10)
                            newsList.add(list[i])

                    }

这种事可以用drop and take

val items = List(30) { i -> "Item ${i+1}"}
items.drop(10).take(10).run(::println)

>> [Item 11, Item 12, Item 13, Item 14, Item 15, Item 16, Item 17, Item 18, Item 19, Item 20]

此外,您无需担心集合中有多少项目 - 如果您担心 drop(69),您最终只会得到一个空列表。如果你做了 listOf(1, 2).take(3),你就会得到 [1, 2]。它们的工作方式类似于“最多 drop/take”——如果您使用负数

,您只会得到一个错误