Scala – Understanding Parameterless and Empty-Paren Methods

scala

I'm learning Scala at the moment via Odersky's Programming Scala (2nd). I'm upto chapter 10 where he starts introducing parameterless and empty-paren methods. I just can't get my head around it.

So far, all I understand is that I should use empty-parens if a method has side-effects and parameterless methods otherwise.

I can't figure out what is the advantage of this convention. I read the posts on Stack Exchange, but to be honest, when the posts start discussing this topic in some depth I was lost.

I'm looking for a simple explanation of what are typical use cases for this language feature and what are the advantages to help me understand it better.

Best Answer

I took your question as why not design the language to prevent the need for a convention in the first place? In other words, why doesn't Scala just force the use of parentheses all the time, instead of allowing programmers to omit them sometimes?

The answer is found in referential transparency. Essentially, if a function has no side effects, a function call can be replaced with its result, without changing the behavior of the program.

That means a function without parameters or side effects is semantically equivalent to a val holding the return value of that function. Because of this property, as a class evolves, the programmer might switch back and forth between using a val or using a function, as convenience or efficiency dictates.

Since you can omit the parentheses, that means code calling something like queue.size doesn't need to know nor care if size is a function or a val. The implementer of the Queue class is therefore free to change between the two without having to change any of the calling code (although I believe it will need recompiling). It stabilizes the public interface of the class. For example, you might start out a queue.size by calling size on an underlying List, which is potentially O(n), then change size to a val for reasons of efficiency.

The convention suggests the parentheses when there are side effects to make it clear that this class member is definitely a function call, and therefore potentially not referentially transparent. It's important for calling code to know if side effects are produced, so they can avoid calling it repeatedly. If you don't care whether it's a function or not, you may as well treat it as if it's not.

Related Topic