What does the following warning mean: 'side-effecting nullary methods are discouraged'?

随声附和 提交于 2019-12-23 07:24:45

问题


I have a lot of nullary methods (methods with 0 parameters) in my scala test file. Hence, instead of writing them as :

def fooBar() = //

I write them as :

def fooBar = //

I get the following warning when I do so:

Warning:(22, 7) side-effecting nullary methods are discouraged: suggest defining as `def fooBar()` instead

What is the meaning of the warning? I am using intelliJ as my IDE and could not really find much about this warning on the web.

EDIT

And, I forgot to mention, when I use the brackets, the warning does not appear.


回答1:


The common convention for nullary methods is to:

  • in case it's a side-effecting method, signify it with use of parenthesis
  • otherwise, drop parenthesis in case it's pure accessor-like method with no side effects

You're breaking this rule and IDE warns you about this.

See also https://stackoverflow.com/a/7606214/298389




回答2:


Does fooBar have side-effects?

It's simply stating a good practice to define a side-effecting method as such:

def fooBar() = ...

And non-side-effecting methods like this:

def fooBar = ...

Since the method call looks similar to accessing a val, it's good to differentiate when the method is doing more than just returning a value.



来源:https://stackoverflow.com/questions/24781394/what-does-the-following-warning-mean-side-effecting-nullary-methods-are-discou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!