scala 将函数作为大括号之间的代码块传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22670356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:09:11  来源:igfitidea点击:

Passing function as block of code between curly braces

scalasyntax

提问by Piotr Sobczyk

A few times I saw a Scala code like that:

有几次我看到这样的 Scala 代码:

object Doer{
   def doStuff(op: => Unit) {
      op
   }
}

Invoked in this way:

以这种方式调用:

Doer.doStuff{
      println("Done")
}

What is strange for me is how a function is passed to another function as just a block of code between curly braces. And there is even no parentheses that normally mark the beginning and end of argument list.

对我来说奇怪的是一个函数如何作为花括号之间的代码块传递给另一个函数。甚至没有通常标记参数列表开始和结束的括号。

What is the name of this Scala syntax/feature? In what cases I can use it? Where is it documented?

这个 Scala 语法/功能的名称是什么?在什么情况下我可以使用它?它在哪里记录?

回答by Dan Simon

This is called either a nullary functionor a thunk, and is an example of call-by-name evaluation: http://www.scala-lang.org/old/node/138

这被称为nullary 函数thunk,并且是按名称评估的示例:http: //www.scala-lang.org/old/node/138

You can use nullaries pretty much anywhere you have a parameter list. They are basically just syntactic sugar around zero-argument functions that make them look like ordinary values, and are invoked whenever they are referenced.

您几乎可以在任何有参数列表的地方使用空值。它们基本上只是围绕零参数函数的语法糖,使它们看起来像普通值,并在引用时被调用。

So

所以

def doSomething(op: => Unit) {
  op
}
doSomething {
  println("Hello!")
}

is exactly the same as:

完全相同:

def doSomething(op: () => Unit) {
  op()
}
doSomething(() => println("Hello!"))

The one thing to keep in mind with nullaries is they are invoked every time they are referenced, so something like:

使用 nullaries 要记住的一件事是,每次引用它们时都会调用它们,例如:

def foo(op: => Int) = op + op
foo {
  println("foo")
  5
}

will print "foo" twice.

将打印“foo”两次。

Edit: To expand on Randall's comment, one of the big ways that a nullary function differs from a zero-arg function is that nullaries are not first-class values. For example, you can have a List[() => Int]but you cannot have a List[=> Int]. And if you had something like:

编辑:为了扩展 Randall 的评论,nullary 函数与零参数函数的主要区别之一是 nullaries 不是一流的值。例如,您可以有 aList[() => Int]但不能有List[=> Int]。如果你有类似的东西:

def foo(i: => Int) = List(i)

you are not adding the nullary function to the list, only its return value.

您没有将 nullary 函数添加到列表中,而只是将其返回值添加到列表中。