richs
richs

Reputation: 4769

in scala why does for yield return option instead of string

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"
  }
}

Upvotes: 0

Views: 313

Answers (3)

Ryan
Ryan

Reputation: 7247

What you're looking for is getOrElse:

opString.getOrElse("error")

This is equivalent to:

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

Upvotes: 0

Nyavro
Nyavro

Reputation: 8866

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]

Upvotes: 1

marstran
marstran

Reputation: 28036

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.

Upvotes: 2

Related Questions