in scala why does for yield return option instead

2019-09-11 03:24发布

问题:

I'm new to scala I'm trying to understand for/yield and don't understand why the following code returns an option not a String

val opString: Option[String] = Option("test")
val optionStr : Option[String] = for {
  op <- opString
} yield {
  opString match {
    case Some(s) => s
    case _ => "error"
  }
}

回答1:

A for-expression is syntactic sugar for a series of map, flatMap and withFilter calls. Your specific for-expression is translated to something like this:

opString.map(op => opString match {
    case Some(s) => s
    case _ => "error"
})

As you can see, your expression will just map over opString and not unwrap it in any way.



回答2:

Desugared expression for your for ... yield expression is:

val optionStr = opString.map {
  op => 
     opString match { 
       case Some(s) => s
       case _ => "error"
     }
}

The type of opString match {...} is String, so the result type of applying map (String => String) to Option[String] is Option[String]



回答3:

What you're looking for is getOrElse:

opString.getOrElse("error")

This is equivalent to:

opString match {
  case Some(s) => s
  case _ => "error"
}


标签: scala