I am trying to create a try clause analogue which repeats code block if exception occurred inside this code block.
def retry(attempts: Int)(func: Unit => Unit) {
var attempt = 0
while (attempt < attempts) {
attempt += 1
try {
func()
} catch {
case _: Throwable =>
}
}
throw new Exception()
}
I expect that it can be used like this
retry(10) { // I would like to pass this block as function
val res = someNotReliableOp(); // <- exception may occur here
print(res)
}
But it doesn't work:
Operations.scala:27: error: type mismatch;
found : Unit
required: Unit => Unit
print(res)
^
one error found
What is the most concise way to pass custom block to my function?
You just need to change your method definition a tiny bit:
def retry(attempts: Int)(func: => Unit)
Unit => Unit
means: a function that takes a parameter with a type of Unit
and evaluates to Unit
.
=> Unit
means: a function that takes no parameters and evaluates to Unit
. This is called call by name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With