Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between dot and space in Scala

Tags:

scala

What precisely is the difference between . and when used to invoke functions from objects in Scala?

For some reason, I get variations, like:

scala> val l:List[Int] = 1::Nil
l: List[Int] = List(1, 2, 3)

scala> l foldLeft(0)((hd, nxt) => hd + nxt) 
<console>:13: error: Int(1) does not take parameters
       | foldLeft(1)((hd, nxt) => hd + nxt)
                    ^
scala>l.foldLeft(0)((hd, nxt) => hd + nxt)
res2: Int = 2

(And while I'm at it, what's the name of that operation? I kept trying to find the strict definition of the . operator and I have no idea what it's called.)

like image 736
linkhyrule5 Avatar asked Mar 12 '23 19:03

linkhyrule5


1 Answers

Having space instead of dot is called postfix notation if there are no arguments in the called function on the object, or infix notation if there is an argument that the function requires.

Postix example: l sum, equivalent to l.sum

Infix example: l map (_ * 2), equivalent to l.map(_ * 2)

The issue with these notations is that they are inherently more ambiguous in their interpretation. A classic example from math:

  • 1 + 2 * 3 + 4 is ambiguous and depends on the priority of the operators.
  • 1.+(2.*(3).+(4) has only one meaningful interpretation.

Therefore it is not a different operator, but the same as the dot, just susceptible to ambiguity that can lead to syntactical errors like your case or even worse logical errors when you chain infix operators.

You can actually express foldLeft with infix notation in this way:

(l foldLeft 0)((hd, nxt) => hd + nxt) 

or even

(0 /: l)((hd, nxt) => hd + nxt)

Where /: is just an alias for foldLeft and makes use of the unique semantics of operator ending in colon(:), which are interpreted as l./:(0) (the reverse of the usual).

like image 119
V-Lamp Avatar answered Mar 20 '23 11:03

V-Lamp