cool breeze
cool breeze

Reputation: 4811

How to handle options with a default

val a = user.type match {
  case Member => doSomething(if(user.location.isDefined) user.location.get.name else "")
}

I want to safely access the user.location which is a Option[Location] if it exists, otherwise just use an empty string.

case class Location(id: Int, name: String)

Is this possible?

Upvotes: 0

Views: 80

Answers (3)

sascha10000
sascha10000

Reputation: 1240

What about this?

val a = user.type match {
  case Member(id, type) if(user.location.isDefined) => doSomething(user.location.get.name)
}

If your Member is a case class with attributes id, type for example.

Upvotes: 0

Scott Shipp
Scott Shipp

Reputation: 2321

Best way to "deep match" into an Option that is nested inside some other object is through a structural pattern match, finally giving a variable name to the desired value and using it in the right side of =>.

I don't know what your "Member" class looks like, but assume that it has two parameters, since we don't care about the first one we put an underscore there "_" and then refer directly to the Location class in the second param, like this:

val a = user match {
  case Member(_, Location(_, Some(name))) => doSomething(name)
}

Upvotes: 3

Jean Logeart
Jean Logeart

Reputation: 53869

Simply:

 doSomething(user.location.map(_.name).getOrElse(""))

Upvotes: 5

Related Questions