Kotlin related but not a Kotlin specific question....
# random
a
Kotlin related but not a Kotlin specific question. I'm trying to understand the difference between regular collections and sequences. Can someone ELI5 the difference between
list.map { it * 2 }
and
list.asSequence().map { it * 2 }.toList()
? Also accepting links to posts/youtube videos that explain it if it's a rabbit hole.
s
Copy code
/**
 * Classes that inherit from this interface can be represented as a sequence of elements that can
 * be iterated over.
 * @param T the type of element being iterated over. The iterator is covariant on its element type.
 */
public interface Iterable<out T> {
    /**
     * Returns an iterator over the elements of this object.
     */
    public operator fun iterator(): Iterator<T>
}
vs
Copy code
public interface Sequence<out T> {
    /**
     * Returns an [Iterator] that returns the values from the sequence.
     *
     * Throws an exception if the sequence is constrained to be iterated once and `iterator` is invoked the second time.
     */
    public operator fun iterator(): Iterator<T>
}
is interesting to me
g
Map on an iterable will traverse the entire list. Sequences are lazy so in certain cases unnecessary operations can be skipped.
a
I guess I'm just even more confused from Stuart's comment where Iterator<> is referenced in both. What do you mean by lazy here @gjesse? How does the language know what the unnecessary operations may be?
e
A sequence will only be computed when you need it, and it will do nothing more then what you need. It can also gives you the power of having a infinite list.
g
here’s a good example, sorry for the bad formatting..
Copy code
kotlin

fun main(args: Array<String>) {
       (0 .. 20).map { 
            println(it)
            it
        }.filter { 
            it % 2 == 0 
        }.first()
    
    
       (0 .. 20)
    	.asSequence()
         .map { 
            println(it)
            it
        }.filter { 
            it % 2 == 0 
        }.first()
    
}
first non-sequence will print 0-> 20
second will only print 0
this is probably more commonly called short-circuiting
a
That's a good example explaining it thank you.
👍 1
a
Also have a look at the documentation for buildSequence (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/build-sequence.html). Some great examples of using Sequences to generate potentially infinite sequences (e.g. Fibonnacii etc)
a
Oh boy I'm gonna have a busy evening tonight