What is the difference between = and := in Scala?
Solution 1:
=
in scala is the actual assignment operator -- it does a handful of specific things that for the most part you don't have control over, such as
- Giving a
val
orvar
a value when it's created - Changing the value of a
var
- Changing the value of a field on a class
- Making a type alias
- Probably others
:=
is not a built-in operator -- anyone can overload it and define it to mean whatever they like. The reason people like to use :=
is because it looks very assignmenty and is used as an assignment operator in other languages.
So, if you're trying to find out what :=
means in the particular library you're using... my advice is look through the Scaladocs (if they exist) for a method named :=
.
Solution 2:
from Martin Odersky:
- Initially we had colon-equals for assignment—just as in Pascal, Modula, and Ada—and a single equals sign for equality. A lot of programming theorists would argue that that's the right way to do it. Assignment is not equality, and you should therefore use a different symbol for assignment. But then I tried it out with some people coming from Java. The reaction I got was, "Well, this looks like an interesting language. But why do you write colon-equals? What is it?" And I explained that its like that in Pascal. They said, "Now I understand, but I don't understand why you insist on doing that." Then I realized this is not something we wanted to insist on. We didn't want to say, "We have a better language because we write colon-equals instead of equals for assignment." It's a totally minor point, and people can get used to either approach. So we decided to not fight convention in these minor things, when there were other places where we did want to make a difference.
from The Goals of Scala's Design
Solution 3:
=
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.
Solution 4:
Scala allows for operator overloading, where you can define the behaviour of an operator just like you could write a method.
As in other languages, =
is an assignment operator.
The is no standard operator I'm aware of called :=
, but could define one with this name. If you see an operator like this, you should check up the documentation of whatever you're looking at, or search for where that operator is defined.
There is a lot you can do with Scala operators. You can essentially make an operator out of virtually any characters you like.