scala - 这两种方法定义有什么区别?

标签 scala

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/

相关文章:

scala - 对象扩展 Trait,类扩展 Trait,两者都必须实现方法

java - 使用 JACKSON 或其他 java 库更改 JSON 键的最佳方法

scala - "traits allow composition"是什么?

scala - 如何在Scala中检查输入变量是否为Int?

scala - 计算向量距 K-means 簇中心的距离

scala - 如何在 SBT 0.10 中声明项目依赖?

scala - Slick:带左连接的查询中的动态 sortBy

scala - 从项的迭代器创建子序列的迭代器

java - 为什么不能将 Scala 对象分配给 Java 变量?

scala - Aux 模式在 Scala 中完成了什么?