y
11/12/2022, 5:25 PMsequence
have an equivalent of Rust’s .next()
for `Iterator`s, which (lazily) returns the next item in the sequence if there is one, or null
otherwise?Chris Lee
11/12/2022, 5:28 PMmap
and filter
operations, and many others that suit specific cases. Sequences are, by design, lazy, so there’s typically no need to check for the next item.y
11/12/2022, 5:32 PM.next()
on the iterator, which is lazily evaluated, and decide what to do based on what is yielded.y
11/12/2022, 5:33 PMChris Lee
11/12/2022, 5:33 PMlistOf("a","b","c").asSequence().map { "mapped-$it" }.filter { it.endsWith("b") }.toList()
y
11/12/2022, 5:33 PMRuckus
11/12/2022, 5:33 PM.take(1).singleOrNull()
Chris Lee
11/12/2022, 5:34 PMChris Lee
11/12/2022, 5:34 PMy
11/12/2022, 5:35 PMy
11/12/2022, 5:35 PMy
11/12/2022, 5:35 PMy
11/12/2022, 5:35 PMy
11/12/2022, 5:36 PMChris Lee
11/12/2022, 5:37 PMval tokenStream = listOf("a","b","c").asSequence()
tokenStream.filter { it.endsWith("b") }.forEach {
// do something with each 'b' token
}
Chris Lee
11/12/2022, 5:37 PMval tokenStream = listOf("a","b","c").asSequence()
tokenStream.filter { it.endsWith("b") }.firstOrNull()
y
11/12/2022, 5:41 PMy
11/12/2022, 5:42 PMChris Lee
11/12/2022, 5:42 PMYoussef Shoaib [MOD]
11/13/2022, 8:54 AMIterator
s are exactly used for this purpose. However, if you want laziness, you'll need to use either `Channel`s or `Flow`s. The former is hot, so you can poll
it and figure out if it has a value ready, and the latter is cold, so it will lazily get the next value, and if it is empty I think there is a build-in way to signal that, so you can return null
theny
11/13/2022, 9:23 AM