Search code examples
scalafunctional-programmingmaxscala-option

How is for comprehension returning None on comparison?


How is a below printed as None as the max is 3 here

val firstNum: Option[Int] = None
val secondNum: Option[Int] = Some(3)

val a = for {
  f <- firstNum
  s <- secondNum

} yield Math.max(f, s)

println(a)

output

None

Solution

  • As in comment section was mentioned, your are using for-comprehension construction, which under the hood invokes flatMap method, which according to left identity monad law always works like this: None.flatmap(f) == None.

    If you you want to find max between two Option[Int] and ignore if any of them absent, try to:

    
    val firstNum: Option[Int] = None
    val secondNum: Option[Int] = Some(3)
    ​
    println(List(firstNum, secondNum).flatten.max)
    

    Scatie: https://scastie.scala-lang.org/UbCy36hHS3iVLKEdqzqUCw