0

I have below piece of code, which is printing: Some(600) as output.

Its not understood how the addition is happening inside 'for' loop.

In below, its confusing whats happening inside the code block of 'for' loop and how the variable 'y' is being calculated. Can someone please help?

 object TestObject extends App
{
  def toInt(s: String): Option[Int] = {
    try
    {
      Some(Integer.parseInt(s.trim))
    }
    catch
      {
        case e: Exception => None
      }
  }
  val y = for
    {
    a <- toInt("100")
    b <- toInt("200")
    c <- toInt("300")
  } yield a + b + c
  println(y)
}
pme
  • 14,156
  • 3
  • 52
  • 95

2 Answers2

2

In Scala this is called a for-comprehension.

toInt wraps the value in an Option which is extracted by <- and assigned to a and so on.

If one of the Option is None the result would be None

yield always returns its last statement, in your case: a + b + c

And so the result is Some(600).

See the documentation here: https://docs.scala-lang.org/tour/for-comprehensions.html

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
pme
  • 14,156
  • 3
  • 52
  • 95
0

From inside the for loop, toInt method is being called which returns an Option[Int]. Now what for loop does is to simply open the Option container and assign variable a with value of 100. On similar lines, variables b and c are assigned value of 200 and 300.

And in the end the yield statement adds the values a,b and c and puts it back in the Option container.

Please refer to https://docs.scala-lang.org/tutorials/FAQ/yield.html and https://alvinalexander.com/scala/scala-for-loop-yield-examples-yield-tutorial

Chaitanya
  • 3,590
  • 14
  • 33