简化方法:将两个选项合并为一个结果

时间:2019-03-20 08:51:01

标签: scala

这可以简化吗?返回值应为Option[State]

updateStateOne(state, "SomeData") match {
    case Some(updatedState) => Some(updateStateTwo(updatedState, "SomeOtherData").getOrElse(updatedState))
    case None               => updateStateTwo(state, "SomeOtherData")
}

我想知道如果没有match ... case,是否有可能?

3 个答案:

答案 0 :(得分:2)

很难说,但是我想这就是你想要的:

updateStateOne(state, "SomeData").fold(updateStateTwo(state, "SomeOtherData")
                                      )(s => updateStateTwo(s, "SomeOtherData"))

答案 1 :(得分:2)

您可以使用其他答案中提到的foldorElse

updateStateOne(state, "SomeData").orElse(Some(state)).map(updateStateTwo(_,"SomeOtherData"))

或者mapgetOrElse(完全等同于fold):

updateStateOne(state, "SomeData").map(s => updateStateTwo(s, "SomeOtherData")).getOrElse(updateStateTwo(state, "SomeOtherData"))

最终,这取决于您的样式首选项以及您的团队发现更多readbale的内容。

答案 2 :(得分:0)

  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")