When to call methods with or without parentheses () in Scala

I ran into this method call quirk in Scala:

If the method has no parameters, you must call it without the parentheses unless the method declaration was defined with empty parentheses.

If you are new to Scala, you’ll probably see this manifest when using iterators.

scala> val wordListIter = wordList.iterator()
:9: error: wordList.iterator of type Iterator[(java.lang.String, java.lang.String)] does not take parameters
scala> val wordListIter = wordList.iterator
wordListIter: Iterator[(java.lang.String, java.lang.String)] = non-empty iterator
scala> val lines= Source.fromPath(filename).getLines
:6: error: missing arguments for method getLines in class Source;
follow this method with `_' if you want to treat it as a partially applied function
Error occured in an application involving default arguments.
val lines= Source.fromPath(filename).getLines
scala> val lines= Source.fromPath(filename).getLines()
lines: Iterator[String] = non-empty iterator

It would have been helpful if the empty parens are listed for the getLines scalaDocs

The convention ensures the uniform access principle. This convention is unlike languages like Ruby where you can call parameter-less methods with or without parentheses.

This except from page 212 of Programming in Scala explains the rationale:

instead of:
def width(): Int
the method is defined without parentheses:
def width: Int

Such parameterless methods are quite common in Scala. By contrast, methods defined with empty parentheses, such as def height(): Int, are called empty-paren methods. The recommended convention is to use a parameterless method whenever there are no parameters and the method accesses mutable state only by reading fields of the containing object (in particular, it does not change mutable state). This convention supports the uniform access principle which says that client code should not be affected by a decision to implement an attribute as a field or method.

About tommychheng
I write a tech blog at http://tommy.chheng.com

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.