Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 854
Tg. Avatar asked Sep 03 '11 16:09

Tg.


People also ask

What does := mean in Scala?

= performs assignment. := is not defined in the standard library or the language specification. It's a name that is free for other libraries or your code to use, if you wish.

What is :: operator in Scala?

The ::() operator in Scala is utilized to add an element to the beginning of the List.

What are the different operators in Scala?

Following are the arithmetic operators that are mostly used in Scala (Source: Operators in Scala): Addition: Adds $(+)$ two variables/operands. Subtraction: Subtracts $(-)$ two operands. Multiplication: Multiplies $(\times)$ two operands.

What does =!= Mean in Scala?

It has no special meaning whatsoever. It is also not a well-known method name in Scala. It seems to come from some library; you need to look at the documentation of whatever library you are using to figure out what it does.


1 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.

like image 139
Lex Avatar answered Sep 21 '22 07:09

Lex