Reputation: 915
Can this be simplified? The return value should be Option[State]
.
updateStateOne(state, "SomeData") match {
case Some(updatedState) => Some(updateStateTwo(updatedState, "SomeOtherData").getOrElse(updatedState))
case None => updateStateTwo(state, "SomeOtherData")
}
I wonder if it's possible without the match ... case
?
Upvotes: 2
Views: 63
Reputation: 4403
def update[S](f: (S, String) => Option[S]): (S, String) => S =
(state, data) => f((state, data)).getOrElse(state)
val s1 = update(updateStateOne)(state, "SomeData")
val s2 = update(updateStateTwo)(s1, "SomeOtherData")
Upvotes: 1
Reputation: 3988
You could use fold
as mentioned in other answers, or orElse
:
updateStateOne(state, "SomeData").orElse(Some(state)).map(updateStateTwo(_,"SomeOtherData"))
Or map
and getOrElse
(which is completely equivalent to fold
):
updateStateOne(state, "SomeData").map(s => updateStateTwo(s, "SomeOtherData")).getOrElse(updateStateTwo(state, "SomeOtherData"))
At the end of the day, it depends on your style preferences and on what your team finds more readable.
Upvotes: 2
Reputation: 51271
It's a little hard to tell, but I think this is what you want:
updateStateOne(state, "SomeData").fold(updateStateTwo(state, "SomeOtherData")
)(s => updateStateTwo(s, "SomeOtherData"))
Upvotes: 2