Search code examples
scalascala-option

Scala, collapsing Option of an Option


Im wondering if there is a short hand for collapsing a map of an option. For example

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))

To fix this I do

val result = Some(6) match {
   case Some(i) => divideByThree(i)
   case None    => None
}

Which seems a bit heavy going. I could create an implicit function on Option say mapOption to deal with this, but am wondering if there is a nicer way I haven't thought of.


Solution

  • You can use flatMap like in:

    def divideByThree(x:Int) = if (x == 0) None else Some(x/3)
    
    val opx = None // Or: Some(10)
    val mapped = opx.flatMap(divideByThree)
    
    println(mapped)