Scala 中的 def foo = {} 和 def foo() = {} 有什么区别? [英] What is the difference between def foo = {} and def foo() = {} in Scala?
问题描述
鉴于以下用于在 Scala 中定义函数的构造,您能解释一下它们之间的区别吗?它们的含义是什么?
Given the following constructs for defining a function in Scala, can you explain what the difference is, and what the implications will be?
def foo = {}
对比
def foo() = {}
更新
感谢您的快速回复.这些都很棒.对我来说唯一的问题是:
Thanks for the quick responses. These are great. The only question that remains for me is:
如果我省略括号,还有办法传递函数吗?这是我在 repl 中得到的:
If I omit the parenthesis, is there still a way to pass the function around? This is what I get in the repl:
scala> def foo = {}
foo: Unit
scala> def baz() = {}
baz: ()Unit
scala> def test(arg: () => Unit) = { arg }
test: (arg: () => Unit)() => Unit
scala> test(foo)
<console>:10: error: type mismatch;
found : Unit
required: () => Unit
test(foo)
^
scala> test(baz)
res1: () => Unit = <function0>
<小时>
更新 2012-09-14
以下是我注意到的一些类似问题:
Here are some similar questions I noticed:
推荐答案
如果在定义中包含括号,则在调用方法时可以选择省略它们.如果在定义中省略它们,则在调用方法时将无法使用它们.
If you include the parentheses in the definition you can optionally omit them when you call the method. If you omit them in the definition you can't use them when you call the method.
scala> def foo() {}
foo: ()Unit
scala> def bar {}
bar: Unit
scala> foo
scala> bar()
<console>:12: error: Unit does not take parameters
bar()
^
此外,您可以对高阶函数执行类似的操作:
Additionally, you can do something similar with your higher order functions:
scala> def baz(f: () => Unit) {}
baz: (f: () => Unit)Unit
scala> def bat(f: => Unit) {}
bat: (f: => Unit)Unit
scala> 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
.这有什么用,我不知道.但它确实表明类型是不同的.
Here baz
will only take foo()
and not bar
. What use this is, I don't know. But it does show that the types are distinct.
这篇关于Scala 中的 def foo = {} 和 def foo() = {} 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!