加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 函数与括号之间的差异,不含

发布时间:2020-12-16 09:39:26 所属栏目:安全 来源:网络整理
导读:Possible Duplicate: 07000 07001 在scala中我们可以定义 def foo():Unit = println ("hello") 要么 def foo:Unit = println ("hello") 我知道他们是不一样的,但有什么区别,哪些应该用在什么时候? 如果这已经回答,请指出我的链接。 解决方法 可以使用或

Possible Duplicate:
07000
07001

在scala中我们可以定义

def foo():Unit = println ("hello")

要么

def foo:Unit = println ("hello")

我知道他们是不一样的,但有什么区别,哪些应该用在什么时候?

如果这已经回答,请指出我的链接。

解决方法

可以使用或不使用括号()来定义0-arity的Scala方法。这用于向用户发出该方法具有某种副作用(如打印输出或破坏数据),而不是以后可以实现为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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读