Sequences: Implementation of the filter
<p>Let’s try to understand the code of the filter decorator. It contains a significant amount of code, so let’s break it down into parts. The decorator takes two parameters as input: <strong><em>sequence</em></strong>, from which it obtains the original iterator, and <strong><em>predicate</em></strong>, which defines the filtering condition (<em>our lambda</em>).</p>
<pre>
internal class FilteringSequence<T>(
private val sequence: Sequence<T>,
private val sendWhen: Boolean = true,
private val predicate: (T) -> Boolean
) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator()
var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue
var nextItem: T? = null</pre>
<p>The essence lies in the implementation of the <strong>hasNext()</strong> method. When this method is called, the decorator invokes the internal <strong>calcNext()</strong> function, which calculates the next element. Essentially, it iterates forward through the original iterator and looks for the first element that satisfies the condition defined in the <strong><em>predicate</em></strong> (<em>our lambda</em>). If it finds the next element that passes the filter, it is stored in the <strong><em>nextItem</em></strong> variable.</p>
<p><a href="https://medium.com/@maxssoft/sequences-implementation-of-the-filter-decorator-de2acefd1d41"><strong>Read More</strong></a></p>