Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 211
dev_android Avatar asked Oct 11 '18 11:10

dev_android


People also ask

What does asSequence do in Kotlin?

Creates a Sequence instance that wraps the original array returning its elements when being iterated. Creates a Sequence instance that wraps the original collection returning its elements when being iterated. Creates a Sequence instance that wraps the original map returning its entries when being iterated.

Why use Sequence in Kotlin?

Kotlin sequences have many more processing functions (because they are defined as extension functions) and they are generally easier to use (this is a result of the fact that Kotlin sequences were designed when Java streams was already used — for instance we can collect using toList() instead of collect(Collectors.

What is the difference between iterable and Sequence in Kotlin?

The order of operations execution is different as well: Sequence performs all the processing steps one-by-one for every single element. In turn, Iterable completes each step for the whole collection and then proceeds to the next step.


1 Answers

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).

like image 60
Adam Arold Avatar answered Oct 27 '22 06:10

Adam Arold