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

查看:18
本文介绍了没有参数的 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天全站免登陆