如何将代码块传递给函数?

tmp*_*ies 4 lambda functional-programming scala currying

我试图创建一个try子句模拟,如果在此代码块内发生异常,则重复代码块.

def retry(attempts: Int)(func: Unit => Unit) {

  var attempt = 0
  while (attempt < attempts) {
    attempt += 1
    try {
      func()
    } catch {
      case _: Throwable =>
    }
  }
  throw new Exception()
}
Run Code Online (Sandbox Code Playgroud)

我希望它可以像这样使用

retry(10) { // I would like to pass this block as function
    val res = someNotReliableOp(); // <- exception may occur here
    print(res)
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用:

Operations.scala:27: error: type mismatch;
 found   : Unit
 required: Unit => Unit
    print(res)
         ^
one error found
Run Code Online (Sandbox Code Playgroud)

将自定义块传递给我的函数的最简洁方法是什么?

Ako*_*chy 8

您只需稍微更改方法定义:

def retry(attempts: Int)(func: => Unit)
Run Code Online (Sandbox Code Playgroud)

Unit => Unit表示:一个函数,它接受一个类型为&Unit且求值为的参数Unit.

=> Unit意思是:一个不带参数和计算结果的函数Unit.这称为名称调用.