I'm pretty new with scala. I skimmed through the book and stumbled these two operators in code. What do they do ?
-
3It depends on the type of the object on the left-hand side. – Arnaud Le Blanc Sep 03 '11 at 16:10
-
Well, I found the code and there have no explanation below or above it. It's just there – Tg. Sep 04 '11 at 05:17
-
As Scala is strongly typed, you should be able to infer the type of the expression. – Raphael Sep 04 '11 at 11:40
2 Answers
Syntactic Sugar
There is some syntactic sugar that applies when using operators in Scala.
Consider an operator *. When compiler encounters a *= b, it will check if method *= is defined on a, and call a.*=(b) if possible. Otherwise the expression will expand into a = a.*(b).
However, any operator that ends with a : will have the right and left arguments swapped when converting to method invocation. So a :: b becomes b.::(a). On the other hand a ::= b becomes a = a.::(b) which could be counter-intuitive due to the lack of the order reversal.
Because of the special meaning, it is not possible to define an operator :. So : is used in conjunction with other symbols, for example :=.
Meaning of Operators
Operators in Scala are defined by the library writers, so they can mean different things.
:: operator is usually used for list concatenation, and a ::= b means take a, prepend b to it, and assign the result to a.
a := b usually means set the value of a to the value of b, as opposed to a = b which will cause the reference a to point to object b.
- 1,184
- 5
- 11
This calls the method : or :: on the object at the left hand side, with the object at the right hand side as argument, and assigns the result to the variable at the left hand side.
foo ::= bar
Is equivalent to
foo = foo.::(bar)
See the documentation for the : or :: method of the object's type.
(For collections, the :: method appends an element to the beginning of the list.)
- 98,321
- 23
- 206
- 194
-
+1 to arnaud. [This question about](http://stackoverflow.com/questions/3181745/understanding-infix-method-call-and-cons-operator-in-scala) **infix method call** could be helpful. – om-nom-nom Sep 03 '11 at 16:17
-
5@arnaud576875 You should mention that it would first try to call the method called `::=` on `foo` if the static type of `foo` defines it, and then fall back to what you’ve described. – Jean-Philippe Pellet Sep 03 '11 at 16:23