Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need parentheses here?

Tags:

scala

Why do I need parentheses around x:Int in this case:

List(1,2,3,4,5).filter((x:Int) => x > 3)

but not x in this case:

List(1,2,3,4,5).filter(x => x > 3)

If I try:

List(1,2,3,4,5).filter(x:Int => x > 3)

I get:

identifier expected but integer literal found

What exactly does that mean?

like image 713
dublintech Avatar asked Jul 18 '26 10:07

dublintech


2 Answers

The parentheses show where the parameter's type ends. Since the => symbol is valid in scala types (indicating a function type), just having the => there doesn't mean that the type is over. Consider this:

List(Map(1->2)).filter((x: Int => Int) => x(1) == 2)

The parentheses clearly show that the first => is part of the type of x and the second is defining the function.

In your second example, there is no type on x, so there's no ambiguity about the role of the =>.

like image 126
dhg Avatar answered Jul 21 '26 02:07

dhg


x: Int => Int - x is function of type Int => Int

(x:Int) => ... - x is function parameter

like image 44
Nazarii Bardiuk Avatar answered Jul 21 '26 02:07

Nazarii Bardiuk