How to combine Option values in Scala?

前端 未结 6 1632
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 03:38

I want to be able to apply an operation f: (T,T) => T to Option[T] values in Scala. I want the result to be None if any of the two

6条回答
  •  星月不相逢
    2020-12-15 04:30

    scala> val (x, y) = (Some(4), Some(9))
    x: Some[Int] = Some(4)
    y: Some[Int] = Some(9)
    
    scala> def f(x: Int, y: Int) = Math.max(x, y)
    f: (x: Int,y: Int)Int
    
    scala> for { x0 <- x; y0 <- y } yield f(x0, y0)
    res26: Option[Int] = Some(9)
    
    scala> val x = None
    x: None.type = None
    
    scala> for { x0 <- x; y0 <- y } yield f(x0, y0)
    res27: Option[Int] = None
    

提交回复
热议问题