Sequences

A Kotlin Sequence is like a List, but you can only iterate through a Sequence—you cannot index into a Sequence. This restriction enables a Sequence to very efficiently perform chained operations.

Operations on Lists are performed eagerly—they always happen right away. For a long chain of List operations, the subsequent operation is started only after the previous result is produced. Here, every element in list is taken through the entire chain of operations:

// Sequences/EagerEvaluation.kt import atomictest.eq fun main(args: Array<String>) { val list = listOf(1, 2, 3, 4) list.filter { it % 2 == 0 } .map { it * it } .any { it < 10 } eq true // Identical to: val mid1 = list.filter { it % 2 == 0 } mid1 eq listOf(2, 4) val mid2 = mid1.map { it * it } mid2 eq listOf(4, 16) mid2.any { it < 10 } eq true }

Eager evaluation is intuitive and straightforward, but can be suboptimal. Because the last operation in EagerEvaluation.kt is any(), it would make more sense to stop after the first matching element is found. For a long sequence, this optimization might be much faster than evaluating every element and then searching for a single match.

End of sample. See AtomicKotlin.com for full early-access book.



Previous          Next

©2018 Mindview LLC. All Rights Reserved.