English 中文(简体)
How would you define a delayed (by-name) parameter that accepts a function that takes parameters?
原标题:

I saw a delayed example in David Pollak s "Beginning Scala". I tried to adapt that, by trial and error. Here s what I have:

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

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

delaying(sayhello())

How would you delay a function/method that takes parameters? Why can t I use parantheses when I call t? Where can I find more documentation on delaying functions?

最佳回答

t does not have to be a function value. It is simply any passed-by-name value that evaluates to Unit.

When you state t in the delaying function, you re not explicitly calling the function that was passed as that parameter. By stating it, you are forcing the passed-by-name parameter to be evaluated, which means sayhello() is evaluated at that point.

There s no reason you can t use parameters in functions in passed-by-name parameters:

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

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

delaying(say("hello"))

The only time you would attach parameters to the t inside delaying would be if its return type was (not Unit but) a function type taking parameters.

问题回答

Since I have a terrible memory and the answer doesn t provide an example how to actually declare a by-name parameter that yields a function taking one or more arguments, I came up with this:

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() )
    }

}




相关问题
Using flag to identify spoken language

In the webapp I am doing, I need to identify language people are speaking. I wanted to use flag to do that. But I have some problems. For example, if you speak French, you can put the French flag. ...

Detecting the browser language of choice with PHP

I m trying to implement this code to have different files to load for german, spanish or english browser languages of choice. The case is that with my spanish IE I still get the english file. <?...

热门标签