我有以下功能:
private def solveError(hostIp: String, command: String) = {
commandSlave(hostIp, "STOP SLAVE") match {
case Success(x) => commandSlave(hostIp, command) match {
case Success(y) => commandSlave(hostIp, "START SLAVE") match {
case Success(z) => Success(z)
case Failure(ex) => Failure(ex)
}
case Failure(ex) => Failure(ex)
}
case Failure(ex) => Failure(ex)
}
}
我认为必须有一种更优雅的方式来编写此函数,但是我不确定该怎么做。使用嵌套的匹配案例并不适合我,但我是Scala的新手,我不知道是否有更好的方法。任何帮助深表感谢。
假设commandSlave
返回Try
,flatMap
则是您想要的:
commandSlave(hostIp, "STOP SLAVE")
.flatMap(_ => commandSlave(hostIp, command))
.flatMap(_ => commandSlave(hostIp, "START SLAVE"))
从scaladocsflatMap
的Try
:
返回应用于此成功值的给定函数,如果失败则返回此函数。
您也可以for
在此处使用推导,它内部消除了与flatMap
s相同的序列:
private def solveError(hostIp: String, serverHost: Host, backHost: Host, command: String) =
for {
_ <- commandSlave(hostIp, "STOP SLAVE")
_ <- commandSlave(hostIp, command)
z <- commandSlave(hostIp, "START SLAVE")
} yield z
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句