Sequences: Implementation of the filter

<p>Let&rsquo;s try to understand the code of the filter decorator. It contains a significant amount of code, so let&rsquo;s break it down into parts. The decorator takes two parameters as input:&nbsp;<strong><em>sequence</em></strong>, from which it obtains the original iterator, and&nbsp;<strong><em>predicate</em></strong>, which defines the filtering condition (<em>our lambda</em>).</p> <pre> internal class FilteringSequence&lt;T&gt;( private val sequence: Sequence&lt;T&gt;, private val sendWhen: Boolean = true, private val predicate: (T) -&gt; Boolean ) : Sequence&lt;T&gt; { override fun iterator(): Iterator&lt;T&gt; = object : Iterator&lt;T&gt; { 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&nbsp;<strong>hasNext()</strong>&nbsp;method. When this method is called, the decorator invokes the internal&nbsp;<strong>calcNext()</strong>&nbsp;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&nbsp;<strong><em>predicate</em></strong>&nbsp;(<em>our lambda</em>). If it finds the next element that passes the filter, it is stored in the&nbsp;<strong><em>nextItem</em></strong>&nbsp;variable.</p> <p><a href="https://medium.com/@maxssoft/sequences-implementation-of-the-filter-decorator-de2acefd1d41"><strong>Read More</strong></a></p>