Reputation: 33
I am new with Scala and I can't figure this out. I am sure it is a simple solution but as a newbie I can't find it.
I have this code
val resID = CartManager.getReservation(request)
val id = if (resID.isDefined && resID.get.status == "FOUND") resID.get.id.toInt else -1
and it gives me an error:
value toInt is not a member of Option[String]
How can I get the id of the object Reservation if it is defined?
Thank you
Upvotes: 2
Views: 9226
Reputation: 12563
That means your id
is Option[String], and not String.
Also, you can use a for-comprehension here.
val id = ( for {
resID <- CartManager.getReservation(request) if resID.status == "FOUND"
theID <- resID.id
} yield theID.toInt ) getOrElse -1
Upvotes: 1
Reputation: 55569
A better functional way to accomplish what you're trying to do would be like this:
val id = CartManager.getReservation(request).filter(_.status == "FOUND").map(_.id.toInt).getOrElse(-1)
Use filter
to filter down the contained Option
value (if it exists), map
to map the CartManager
to an Option[Int]
, and getOrElse
to extract the value from the Option
with the default value -1
if the Option
is empty.
Upvotes: 4