如果我们可以不使用括号来定义不需要任何参数的函数,为什么在 Scala 中使用空括号? [英] Why to use empty parentheses in Scala if we can just use no parentheses to define a function which does not need any arguments?

查看:21
本文介绍了如果我们可以不使用括号来定义不需要任何参数的函数,为什么在 Scala 中使用空括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在 Scala 中,我们可以定义一个没有参数的函数,要么在函数名称后使用空括号,要么根本没有括号,这两个定义不是同义词.区分这 2 种语法的目的是什么,我什么时候应该更好地使用一种而不是另一种?

As far as I understand, in Scala we can define a function with no parameters either by using empty parentheses after its name, or no parentheses at all, and these two definitions are not synonyms. What is the purpose of distinguishing these 2 syntaxes and when should I better use one instead of another?

推荐答案

这主要是一个约定问题.按照惯例,具有空参数列表的方法会评估其副作用.假设没有参数的方法没有副作用.这就是约定.

It's mostly a question of convention. Methods with empty parameter lists are, by convention, evaluated for their side-effects. Methods without parameters are assumed to be side-effect free. That's the convention.

这篇关于如果我们可以不使用括号来定义不需要任何参数的函数,为什么在 Scala 中使用空括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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