Scala: what do ":=" and "::=" operator do?
I'm pretty new with 开发者_如何学编程scala. I skimmed through the book and stumbled these two operators in code. What do they do ?
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.
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.)
加载中,请稍侯......
精彩评论