I tried following two versions of code to understand how yield in scala works. I am unable to understand why I am getting two different results
In this version, I call yield and the expression is simply multiply by 2. I get a Vector of 1st 10 multiples of 2. It makes sense to me
scala> val r = for (j <- 1 to 10) yield {
| (j*2).toString //multiply by 2
| }
r: scala.collection.immutable.IndexedSeq[String] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20) // got multiples of 2. This looks ok
Interestingly in this version, all I have done is store the multiplication by 2 in a val. But now I get an empty vector! Why is this?
scala> val r = for (j <- 1 to 10) yield {
| val prod = (j*2).toString //multiply by 2 but store in a val
| }
r: scala.collection.immutable.IndexedSeq[Unit] = Vector((), (), (), (), (), (), (), (), (), ()) //this is empty
I thought that maybe the val prod = (j*2).toString results in a Unit result but when I try following independent expression on scala interpreter, I can see that prod is a String
scala> val prod = 2.toString()
prod: String = 2