Reputation: 4811
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
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
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
Reputation: 53869
Simply:
doSomething(user.location.map(_.name).getOrElse(""))
Upvotes: 5