Reputation: 16214
In scala, I have a map.
I want to ask for an object - say a Train - from my map. Then I want to call the, say, "getNumberOfCarriages" method on my Train.
If I don't know if the map has an entry for the key value "Thomas", how, in scala, do I safely query for the number of carriages, or return some default value (for the sake of the example, 0?)
ie how do i call
myMap.get("Thomas").getNumberOfCarriages()
I've seen a getOrElse
method, but I am uncertain if it is applicable to the problem?
Upvotes: 0
Views: 41
Reputation: 51271
One thing you could do is lift
it to an Option
and then fold
over it to get either the number of carriages or a default value if None
.
myMap.lift("Thomas").fold(0)(_.getNumberOfCarriages())
Upvotes: 3