Why do I get the output of the below Scala code snippet as List((), (), (), ()) :
val ans1 = for(i3 <- 1 to 4) yield {
if (i3 % 2 == 0)
i3
}
I tried the below :
val ans1 = for(i3 <- 1 to 4) yield {
if (i3 % 2 == 0)
i3
}
Expected:
List(2,4)
If
thenExprandelseExprhave typeAthenif (condition) thenExpr else elseExprhas typeAtoo.If
thenExprandelseExprhave different types thenif ...has their supertype.If
elseExpris omitted thenif (condition) thenExpris a shorthand forif (condition) thenExpr else (), where()has typeUnit. So ifthenExprhas typeUnitthenif (condition) thenExprhas typeUnit, otherwiseif (condition) thenExprhas a type, which is supertype of some type (the one ofthenExpr) andUniti.e.AnyorAnyVal.That's where those
()are from and why the return type isSeq[AnyVal]rather thanSeq[Int].Just don't omit
elsepart. Also you can use standard methods.map,.filter. For-comprehensions are desugared into them.As @Always_A_Learner and @Dima advised, you can try