marstran
12/16/2019, 4:52 PMfun main() {
var curr = listOf(1).asSequence()
curr = curr.map { curr.sum() }
println(curr.sum())
}
While this works fine:
fun main() {
var curr = listOf(1).asSequence()
val done = curr.map { curr.sum() }
println(done.sum())
}
Do anyone know why this happens? It also works if I remove the sum
inside the map
. The weird thing is that it makes a difference whether I assign the result to a new variable or not.molikuner
12/16/2019, 4:59 PMwbertan
12/16/2019, 5:00 PM@Test
fun asas() {
println("start")
var curr = listOf(1).asSequence()
println("created curr")
curr = curr.map {
println("going to do the sum inside the map")
curr.sum().also { println("doing the sum inside map") }
}
println("going to do the last sum")
println(curr.sum())
}
Will produce
start
created curr
going to do the last sum
going to do the sum inside the map
going to do the sum inside the map
going to do the sum inside the map
going to do the sum inside the map (and this until StackOverFlow)
molikuner
12/16/2019, 5:02 PMwbertan
12/16/2019, 5:02 PMpublic final void asas2() {
final ObjectRef curr = new ObjectRef();
curr.element = CollectionsKt.asSequence((Iterable)CollectionsKt.listOf(1));
curr.element = SequencesKt.map((Sequence)curr.element, (Function1)(new Function1() {
// $FF: synthetic method
// $FF: bridge method
public Object invoke(Object var1) {
return this.invoke(((Number)var1).intValue());
}
public final int invoke(int it) {
return SequencesKt.sumOfInt((Sequence)curr.element);
}
}));
int var2 = SequencesKt.sumOfInt((Sequence)curr.element);
boolean var3 = false;
System.out.println(var2);
}
public final void asas3() {
final ObjectRef curr = new ObjectRef();
curr.element = CollectionsKt.asSequence((Iterable)CollectionsKt.listOf(1));
Sequence done = SequencesKt.map((Sequence)curr.element, (Function1)(new Function1() {
// $FF: synthetic method
// $FF: bridge method
public Object invoke(Object var1) {
return this.invoke(((Number)var1).intValue());
}
public final int invoke(int it) {
return SequencesKt.sumOfInt((Sequence)curr.element);
}
}));
int var3 = SequencesKt.sumOfInt(done);
boolean var4 = false;
System.out.println(var3);
}
The asas2
is the one with problem, the asas3
is the other one “without” the problem.marstran
12/16/2019, 5:03 PMmap
is actually executed (triggered by the final sum), the reference to curr
has already changed.marstran
12/16/2019, 5:04 PMfun main() {
var curr = listOf(1).asSequence()
val capture = curr
curr = curr.map { capture.sum() }
println(curr.toList())
}
wbertan
12/16/2019, 5:04 PMasas2
(with the problem), it is adding the map
operation as an element
in the sequence, would that make a difference when the `map`executes, and getting “lost” in how many times it needs to execute?