在Scala中,def foo = {}和def foo() = {}有什么区别?

来源:互联网 发布:嘀哩嘀哩 知乎 编辑:程序博客网 时间:2024/06/03 23:46

原文:https://gxnotes.com/article/83516.html

问题描述

给定以下用于在Scala中定义函数的结构,你可以解释什么是区别,它将会有什么影响?

def foo = {}

def foo() = {}

更新

感谢您的快速回复。这些都很棒对我来说唯一的问题是:

如果省略括号,还有一种方法来传递函数吗?这是我得到的副本:

scala> def foo = {}foo: Unitscala> def baz() = {}baz: ()Unitscala> def test(arg: () => Unit) = { arg }test: (arg: () => Unit)() => Unitscala> test(foo)<console>:10: error: type mismatch; found   : Unit required: () => Unit              test(foo)                   ^scala> test(baz)res1: () => Unit = <function0>

更新2012-09-14

这里有一些类似的问题我注意到:

  1. Difference between function with parentheses and without

  2. Scala methods with no arguments

最佳解决方案

如果在定义中包含括号,则可以在调用该方法时选择性地省略它们。如果您在定义中省略它们,则在调用该方法时不能使用它们。

scala> def foo() {}foo: ()Unitscala> def bar {}bar: Unitscala> fooscala> bar()<console>:12: error: Unit does not take parameters       bar()          ^

此外,您可以执行类似于您的高阶功能的操作:

scala> def baz(f: () => Unit) {}baz: (f: () => Unit)Unitscala> def bat(f: => Unit) {}bat: (f: => Unit)Unitscala> baz(foo)    scala> baz(bar)<console>:13: error: type mismatch; found   : Unit required: () => Unit       baz(bar)           ^scala> bat(foo)scala> bat(bar)  // both ok

这里baz只能使用foo()而不是bar。这是什么用的,我不知道。但它确实表明,类型是不同的。

次佳解决方案

让我复制我的答案我张贴在a duplicated question:

可以使用或不使用括号()定义0级的Scala方法。这用于向用户发出该方法具有某种类型的side-effect(如打印输出或破坏数据),而不是以后可以实现为val

见Programming in Scala:

Such parameterless methods are quite common in Scala. By contrast, methods defined with empty parentheses, such as def height(): Int, are called empty-paren methods. The recommended convention is to use a parameterless method whenever there are no parameters and the method accesses mutable state only by reading fields of the containing object (in particular, it does not change mutable state).

This convention supports the uniform access principle […]

To summarize, it is encouraged style in Scala to define methods that take no parameters and have no side effects as parameterless methods, i.e., leaving off the empty parentheses. On the other hand, you should never define a method that has side-effects without parentheses, because then invocations of that method would look like a field selection.

参考文献

  • What is the difference between def foo = {} and def foo() = {} in Scala?

原创粉丝点击