Why can't yield a value here

val li = List(3,2,1,4,"1",'a')

for ( x <- li ) {
  val y = x match {
    case z:Int => z + 1
    case _ => x
  }
} yield y

This doesn’t work. please help look at it. :slight_smile:

You are mixing two different sugar syntaxes (yeah I know, I like to rant about the excessive amount of sugar syntax of the language).

There are two variations of the for comprehension syntax.

for {
 foo <- generator1
 ...
 bar <- generatorN
} yield baz
// This one desugars to flatMap & map calls.
// You may also add if statements in the middle which will desugar to withFilter

for (foo <- generator1; ...; bar <- generatorN) {
   baz(...)
}
// This one desugars to foreach

You are trying to mix the two, which doesn’t work.
Rather you can do:

for {
  x <- li
  y = x match {
    case z:Int => z + 1
    case _ => x
  }
} yield y

// Or even better IMHO
li.map {
  case z: Int => z + 1
  case x => x
}

(PS: A List[Any] is a code smell, you should not have to do this in any case)


This is actually a FAQ: Scala FAQ | Scala Documentation

3 Likes

Hello @BalmungSan

for this two styles which one i should use?

scala> val result = for (e <- a) yield 2*e
val result: Array[Int] = Array(4, 6, 10, 14)

scala> val result = for (e <- a; z=2*e) yield z
val result: Array[Int] = Array(4, 6, 10, 14)

regards.

I have never seen anyone use an assignment inside parenthesis.

Now, if we compare:

val result =
  for {
    e <- a
  } yield 2*e

VS

val result =
  for {
    e <- a
    z = 2*e
  } yield z

I would say there is no point in creating an additional variable name.


Now, again, I personally don’t like for that much and i would rather just use map here.

1 Like
scala> def mytest(s:String="hello") = {
     |    println(s)
     | }
def mytest(s: String): Unit

That is not an assignment; that is a default value for an argument.

Also, I mean punctually the for syntax that uses parenthesis, not parenthesis in general.

Ok thanks. got it.