Sequences: Implementation of the map decorator

Max Sidorov
1 min readOct 27, 2023

The decorator for the map is designed very simply. It takes the sequence parameter as input, which contains the original iterator that we want to decorate, and the transformer function. This transformer function is essentially the lambda expression { it + 1 } that is executed inside the map function.

The original iterator that we want to decorate is obtained from the sequence parameter and is stored in an internal variable iterator.

constructor(private val sequence: Sequence<T>, private val transformer: (T) -> R) : Sequence<R> {

override fun iterator(): Iterator<R> = object : Iterator<R> {

val iterator = sequence.iterator()

override fun next(): R {
return transformer(iterator.next())
}

override fun hasNext(): Boolean {
return iterator.hasNext()
}
}
}

On each call to the next() method, the original iterator iterator.next() is invoked, and the obtained value is passed through the transformer function (our lambda).

override fun next(): R {
return transformer(iterator.next())
}

Thus, with each call to next(), we will get the transformed element of the original sequence as output.

You can learn more from my sequences performance study “Measuring sequences”

--

--

Max Sidorov

Android lead at SberDevices. I like programming and exploring the internals of Kotlin.