How to combine Option values in Scala?

前端 未结 6 1634
佛祖请我去吃肉
佛祖请我去吃肉 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:17

    I have a slightly older version of scalaz than retronym but the following works for me as an example and is generalizable for the case where you have 3 types T, U, V and not just one:

    def main(args: Array[String]) {
      import scalaz._
      import Scalaz._
    
      val opt1 = some(4.0) //Option[Double]
      val opt2 = some(3)   //Option[Int]
    
      val f: (Double, Int) => String = (d, i) => "[%d and %.2f]".format(i, d)
    
      val res = (opt1 <|*|> opt2).map(f.tupled)
      println(res) //Some([3 and 4.00])
    }
    

    I can then add:

    val opt3 = none[Int]
    val res2 = (opt1 <|*|> opt3).map(f.tupled)
    println(res2) //None
    

提交回复
热议问题