没有参数的Scala方法 [英] Scala methods with no arguments

查看:162
本文介绍了没有参数的Scala方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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")

这两种方法完全相同,但是(2)可以带或不带括号调用.

These two methods are exactly same but (2) can be called with and without parentheses.

Scala允许使用此功能是否有任何特殊原因,使我困惑使用哪个功能以及何时使用?

Is there any special reason for which this feature is allowed in Scala.It confuses me which to use and when?

推荐答案

一般规则是,只要方法(非函数)有副作用,则应在声明站点和调用站点两者处添加一个空参数列表.

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.

否则,Scala具有统一的访问原则,因此客户端无需知道他们是在访问字段还是在调用无副作用方法.

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.

这篇关于没有参数的Scala方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆