在大括号之间将函数作为代码块传递 [英] Passing function as block of code between curly braces

查看:45
本文介绍了在大括号之间将函数作为代码块传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

A few times I saw a Scala code like that:

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

以这种方式调用:

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.

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

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

推荐答案

这被称为空函数thunk,是的一个例子按名称调用评估:http://www.scala-lang.组织/旧/节点/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.

所以

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

完全一样:

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

对于 nullaries 要记住的一件事是它们在每次被引用时都会被调用,比如:

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

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

将打印foo"两次.

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

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:

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

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

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

这篇关于在大括号之间将函数作为代码块传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆