I have the following function:
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)
}
}
I think there must be a more elegant way to write this function but I'm not sure how. Using nested match cases doesn't feel right to me but I'm new to Scala and I don't know if there is a better way. Any help is much appreciated.
Assuming that commandSlave
returns Try
, flatMap
is what you want:
commandSlave(hostIp, "STOP SLAVE")
.flatMap(_ => commandSlave(hostIp, command))
.flatMap(_ => commandSlave(hostIp, "START SLAVE"))
From scaladocs of flatMap
of Try
:
Returns the given function applied to the value from this Success or returns this if this is a Failure.
Also you can use for
comprehension here, which internally desugars to the same sequence of 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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments