不带参数的 Scala 方法
在 Scala 中,有两种方法可以定义不带参数的方法。
1 def a=println("hello")
2 def a()=println("hello")
这两种方法完全相同,但是 (2) 可以带括号调用,也可以不带括号调用。
Scala 中允许使用此功能是否有任何特殊原因。它让我困惑于何时使用哪个?
In Scala there are two ways to define a method which takes no argument
1 def a=println("hello")
2 def a()=println("hello")
These two methods are exactly same but (2) can be called with and without parentheses.
Is there any special reason for which this feature is allowed in Scala.It confuses me which to use and when?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般规则是,只要方法(而不是函数)有副作用,您就应该在声明站点和调用站点添加一个空参数列表。
除此之外,Scala 具有统一的访问原则,因此客户端不需要知道他们是在访问字段还是在调用无副作用的方法。
The general rule is that you should add an empty parameter list at both declaration site and call site whenever the method (not function) has side effects.
Otherwise, Scala has the uniform access principle, so that clients don't need to know whether they're accessing a field or calling a side-effect-free method.
允许使用不带括号的语法,因此可以这样写:
在
X
上调用f
的代码不需要知道它是否是val
或def
。调用空列表方法时可以省略括号的原因是允许调用理想情况下不带括号的 Java 方法(但是,因为它们是 Java,所以它们都有括号)。
正如其他人所说,当方法有副作用时,有一个约定,即使用空参数列表,否则将其保留。
The syntax without parenthesis is allowed so one can write this:
A code calling
f
on anX
does not need to know if it is aval
or adef
.The reason why one can omit parenthesis when calling methods with an empty list is to allow calling Java methods that would ideally not have parenthesis (but, because they are Java, they all have parenthesis).
As other said, there's a convention of using an empty parameter list when the method has side effects, and leaving them off otherwise.
是否选择使用括号来指示有副作用的方法调用是一个风格问题。
顺便说一句,如果您使用
=
声明一个纯粹的副作用方法,您可能应该显式声明一个Unit
返回类型,如下所示:请注意,任何类型都可以被强制到
单位
。如果您不想显式声明返回类型,则可能应该省略
=
。然后编译器将推断出Unit
的返回类型,即使最后一个表达式返回不同的内容:上述两种风格都使重构更安全,因为修改方法体永远不会导致编译器推断出不同的类型返回类型。在我看来,这种声明的明确性比调用站点代码风格更重要。
It's a matter of style whether you choose to use parentheses to indicate a side-effecting method call.
By the way, if you declare a purely side-effecting method using
=
, you should probably explicitly declare aUnit
return type, like this:Note that any type can be coerced to
Unit
.If you do not want to explicitly declare a return type, you should probably omit the
=
. Then the compiler will infer a return type ofUnit
, even if the last expression returns something different:Both of the above styles make refactoring safer, because modifying the method body will never cause the compiler to infer a different return type. IMO this explicitness of declaration is more important than call-site code style.