kotlinsequence

Advantage of adding asSequence() in Array in Kotlin


Anyone can help me pointing out the difference between the use of asSequence() in the following piece of code.

val numbers = 1 .. 50
val output = numbers.filter{ it < 10 }.map{ Pair("Kotlin", it)}
output.forEach(::println)

Adding asSequence()

val numbers = 1 .. 50
val output = numbers.asSequence().filter{ it < 10 }.map{ Pair("Kotlin", it)}
output.forEach(::println)

Solution

  • The difference is that when you use a Sequence it will only run the functions if you iterate over the elements. So for example this:

    val numbers = 1 .. 50
    val output = numbers.asSequence().filter{
        println("Filtering $it")
        it < 10
    }.map{
        println("Mapping $it")
        Pair("Kotlin", it)
    }
    

    will print nothing, because you did not iterate over output.

    Checking the docs helps:

    /**
     * Creates a [Sequence] instance that wraps the original collection
     * returning its elements when being iterated.
     */
    public fun <T> Iterable<T>.asSequence(): Sequence<T> {
        return Sequence { this.iterator() }
    }
    

    Using Sequences is useful because if you just call map on a Collection the result will be converted to a List and with a Sequence you can avoid these conversion steps. Think about Sequences like Streams in the Java Stream API (with the difference that Kotlin's solution does not support parallel execution).