1. Methods with Empty Argument Lists
If a method takes no parameters, you can define it without parentheses. Callers must invoke the method without parentheses. Conversely, if you add empty parentheses to your definition, callers have the option of adding parentheses or not.
For example, List.size
has no parentheses, so you write List(1, 2, 3).size
. If you try List(1, 2, 3).size()
, you’ll get an error.
Scala would prefer that definition and usage remain consistent, but it’s more flexible when the definition has empty parentheses, so that calling Java no-argument methods can be consistent with calling Scala no-argument methods.
A convention in the Scala community is to omit parentheses for no-argument methods that have no side effects, like the size
of a collection. When the method performs side effects, parentheses are usually added, offering a small “caution signal” to the reader that mutation might occur, requiring extra care.
2. Methods with One Argument Lists
Let’s see the following example:
scala> def isEven(n: Int) = (n%2) == 0
isEven: (n: Int)Boolean
scala> List(1, 2, 3, 4).filter(isEven).foreach(println)
2
4
We can shorten it as follows:
List(1, 2, 3, 4) filter isEven foreach println
(The .
operator is omitted)
To be clear, this expression works because each method we used took a single argument. If you tried to use a method in the chain that takes zero or more than one argument, it would confuse the compiler. In those cases, put some or all of the punctuation back in.
Ref