Scala: what do the operations :: "and" :: = "do?

I am new to scala. I looked through the book and came across these two statements in code. What are they doing?

+4
source share
2 answers

Syntactic sugar

There is some syntactic sugar that is used when using operators in Scala.

Consider the operator * . When the compiler encounters a *= b , it checks to see if the *= method exists on a , and call a.*=(b) if possible. Otherwise, the expression will expand to a = a.*(b) .

However, any statement that ends with : will have the right and left arguments replaced when converted to a method call. So a :: b becomes b.::(a) . On the other hand, a ::= b becomes a = a.::(b) , which can be counter-intuitive due to the lack of access to order.

Due to the special meaning, it is not possible to define the operator : Thus : used in combination with other characters, for example := .

The value of the operators

Operators in Scala are defined by library writers, so they can mean different things.

Operator

:: usually used to concatenate a list, 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 , unlike a = b , which will call the reference a to point to object b .

+13
source

This calls the method : or :: object on the left, and the object on the right as an argument, and assigns the result to the variable on the left.

 foo ::= bar 

Is equivalent

 foo = foo.::(bar) 

See the documentation for the method : or :: for the type of object.

(For collections, the :: method adds an item to the top of the list.)

+3
source

All Articles