15

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)
Demigod
  • 5,073
  • 3
  • 31
  • 49
dev_android
  • 8,698
  • 22
  • 91
  • 148
  • 1
    your snippets are identical – Tim Oct 11 '18 at 11:30
  • 1
    See also: [Kotlin's Iterable and Sequence look exactly same. Why are two types required?](https://stackoverflow.com/questions/35629159/kotlins-iterable-and-sequence-look-exactly-same-why-are-two-types-required) – hotkey Oct 11 '18 at 14:14

1 Answers1

21

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

Adam Arold
  • 29,285
  • 22
  • 112
  • 207