Manu Chadha
Manu Chadha

Reputation: 16755

removing parenthesis if method has no argument/no side effects

I read that if a method takes no argument and has no side-effects, parenthesis can be removed to improve readability (spartan implementation). So I can call following code

def withoutP = {
        println(s"without p")
    }
withoutP

Then I found this code which takes arguments but I can still call it without parenthesis. How?

def isEven(n: Int) = (n % 2) == 0
List(1, 2, 3, 4) filter isEven foreach println

I tried running this code but it didn't work. Why?

def withP(i:Int) = {

    println("with p")
}
withP 1

';' expected but integer literal found.
[error]                 withP 1
[error]                       ^
[error] one error found

Upvotes: 0

Views: 70

Answers (2)

chengpohi
chengpohi

Reputation: 14227

1.For first example, invoke withoutP without parameter, this compiles is by Scala allows the omission of parentheses on methods of arity-0 (no arguments)

2.For second example, invoke withoutP 1 with a parameter, this not compile is caused by Infix notation need to start with a object. so you can achieve parentheses by:

this withP 1 //infix notation with this (current object)

so for the 1 and 2 are not the same omission parentheses rules. First is the arity-0 rule, and Second should use Infix notation to omit parentheses.

Upvotes: 1

Arjan
Arjan

Reputation: 9884

In your example

def isEven(n: Int) = (n % 2) == 0
List(1, 2, 3, 4) filter isEven foreach println

you don't actually call isEven. You call filter, which is a method on List, and isEven is the parameter for filter. filter calls isEven for every value in the list, using the value as the argument.

filter is written in the infix notation, which is legal for methods that accept only one argument. The alternative is

List(1, 2, 3, 4).filter(isEven)

The . is also required in this case, because filter is a method in the List class.

Upvotes: 2

Related Questions