为什么要在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?

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

问题描述

就我所知,在Scala中我们可以通过在名称后面使用空括号或根本不使用括号来定义一个没有参数的函数,而这两个定义不是同义词。区分这两种语法的目的是什么?什么时候应该更好地使用一种而不是另一种?解析方案

这主要是一个问题惯例。按照惯例,带有空白参数列表的方法评估其副作用。假定没有参数的方法是无副作用的。这是公约。

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天全站免登陆