我想知道是否有折叠选项地图的短手。例如
def divideByThree(x:Int) = if (x == 0) None else Some(x/3)
val result = Some(6) map (divideByThree(_))
resut:Option[Option[Int]] = Some(Some(2))
为了解决这个问题,我做
val result = Some(6) match {
case Some(i) => divideByThree(i)
case None => None
}
这似乎有点沉重。我可以在 Option 上创建一个隐式函数说 mapOption 来处理这个问题,但我想知道是否有更好的方法我没有想到。