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 thenExpr
and elseExpr
have type A
then if (condition) thenExpr else elseExpr
has type A
too.
If thenExpr
and elseExpr
have different types then if ...
has their supertype.
If elseExpr
is omitted then if (condition) thenExpr
is a shorthand for if (condition) thenExpr else ()
, where ()
has type Unit
. So if thenExpr
has type Unit
then if (condition) thenExpr
has type Unit
, otherwise if (condition) thenExpr
has a type, which is supertype of some type (the one of thenExpr
) and Unit
i.e. Any
or AnyVal
.
That's where those ()
are from and why the return type is Seq[AnyVal]
rather than Seq[Int]
.
Just don't omit else
part. Also you can use standard methods .map
, .filter
. For-comprehensions are desugared into them.
As @Always_A_Learner and @Dima advised, you can try
val ans1 = for(i3 <- 1 to 4 if i3 % 2 == 0) yield i3