Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a code block to function?

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?

like image 977
tmporaries Avatar asked Jan 16 '14 18:01

tmporaries


1 Answers

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.

like image 114
Akos Krivachy Avatar answered Oct 26 '22 12:10

Akos Krivachy