2

delayed在 David Pollak 的"Beginning Scala". 我试图通过反复试验来适应这一点。这是我所拥有的:

def sayhello() = {
  println("hello")
}

def delaying(t: => Unit):Unit = {
  println("before call")
  t
  println("after call")
}

delaying(sayhello())

您将如何延迟带参数的函数/方法?为什么我打电话时不能使用括号t?我在哪里可以找到更多关于延迟函数的文档?

4

2 回答 2

5

t不必是函数值。它只是计算结果为的任何按名称传递的值Unit

当您tdelaying函数中声明时,您没有显式调用作为该参数传递的函数。通过说明它,您将强制对按名称传递的参数进行评估,这意味着sayhello()在该点进行评估。

没有理由不能在按名称传递的参数中使用函数中的参数:

def say(word: String) {
  println(word)
}

def delaying(t: => Unit) {
  println("before call")
  t
  println("after call")
}

delaying(say("hello"))

唯一将参数附加到t内部的delaying情况是它的返回类型是(不是Unit但)带参数的函数类型。

于 2009-12-15T17:33:03.240 回答
1

由于我的记忆力很差,并且答案没有提供示例如何实际声明一个按名称参数生成的函数,该函数采用一个或多个参数,所以我想出了这个:

object DelayedEvalTest {

    private class DelayedFunction extends Function1[Int,Unit] {

        override def apply(x:Int) : Unit = {}

        println("function created")
    }

    private def eval(eval:Boolean, op : Int => Unit ) {
        println("in eval()")
        if ( eval ) {
            op( 42 )
        }
    }

    private def evalDelayed(eval:Boolean, op : => Int => Unit ) {
        println("in evalDelayed()")
        if ( eval ) {
            op( 42 )
        }
    }

    def main(args:Array[String]) {
        eval( false , new DelayedFunction() )
        evalDelayed( false , new DelayedFunction() )
    }

}
于 2010-05-16T09:43:32.597 回答