Possible Duplicate:
Why to use empty parentheses in Scala if we can just use no parentheses to define a function which does not need any arguments?
假设我们有一个类 Foo
使用方法bar
(它不带参数并返回字符串 "bar"
)。 bar有两种实现方式
第一个是
class Foo {
def bar() = "bar"
}
第二个是
class Foo {
def bar = "bar"
}
虽然两者的作用基本相同,但它们需要以不同的方式调用,第一个像这样
someFoo.bar()
还有第二个
someFoo.bar
为什么我应该使用其中一种而不是另一种,根本区别是什么?
最佳答案
定义不带参数且不带括号的方法意味着该方法是纯方法(它没有副作用,并且不依赖于程序的状态)。此类方法不能用括号调用:
class Square(val side: Int) {
def area = side * side
}
s = new Square(10);
s.area //ok
s.area() //compilation error
调用不带括号的参数的方法意味着该方法有一些副作用并且返回类型为 Unit
。使用空括号定义的方法可以在有或没有空括号的情况下调用。
class Foo {
def bar(): Unit = println("bar")
}
f = new Foo();
f.bar; //ok, bad style
f.bar(); // good
关于scala - 这两种方法定义有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12884841/