Contents of file A.scala
:
object A {
val doubleEven1 = for (i <- 1 to 10; if i % 2 == 0) yield i * 2
}
Output of scalac -Xprint:jvm A.scala
:
[[syntax trees at end of jvm]]// Scala source: A.scala
package <empty> {
final class A extends java.lang.Object with ScalaObject {
private[this] val doubleEven1: scala.collection.immutable.IndexedSeq = _;
<stable> <accessor> def doubleEven1(): scala.collection.immutable.IndexedSeq = A.this.doubleEven1;
def this(): object A = {
A.super.this();
A.this.doubleEven1 = scala.this.Predef.intWrapper(1).to(10).withFilter({
(new A$$anonfun$1(): Function1)
}).map({
(new A$$anonfun$2(): Function1)
}, immutable.this.IndexedSeq.canBuildFrom()).$asInstanceOf[scala.collection.immutable.IndexedSeq]();
()
}
};
@SerialVersionUID(0) @serializable final <synthetic> class A$$anonfun$1 extends scala.runtime.AbstractFunction1$mcZI$sp {
final def apply(i: Int): Boolean = A$$anonfun$1.this.apply$mcZI$sp(i);
<specialized> def apply$mcZI$sp(v1: Int): Boolean = v1.%(2).==(0);
final <bridge> def apply(v1: java.lang.Object): java.lang.Object = scala.Boolean.box(A$$anonfun$1.this.apply(scala.Int.unbox(v1)));
def this(): A$$anonfun$1 = {
A$$anonfun$1.super.this();
()
}
};
@SerialVersionUID(0) @serializable final <synthetic> class A$$anonfun$2 extends scala.runtime.AbstractFunction1$mcII$sp {
final def apply(i: Int): Int = A$$anonfun$2.this.apply$mcII$sp(i);
<specialized> def apply$mcII$sp(v1: Int): Int = v1.*(2);
final <bridge> def apply(v1: java.lang.Object): java.lang.Object = scala.Int.box(A$$anonfun$2.this.apply(scala.Int.unbox(v1)));
def this(): A$$anonfun$2 = {
A$$anonfun$2.super.this();
()
}
}
}
As you can see the compiler creates a Range
from 1 to 10. Then it calls the withFilter
on that Range
to filter all even numbers. And the last step is the call of the map
-method with the multiplication with 2.
Would your second example work the semantic would be a little bit different. Because it would execute the body of the loop in every iteration without filtering.
It is a matter of taste but I would prefer this:
val doubleEven = 1 to 10 filter(_%2==0) map(_*2)