What is the difference between = and := in Scala?

15.1k views Asked by At

What is the difference between = and := in Scala?

I have googled extensively for "scala colon-equals", but was unable to find anything definitive.

4

There are 4 answers

1
Owen On BEST ANSWER

= 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 or var 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 :=.

0
Rex Kerr On

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

1
tolitius On

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

1
thomasrutter On

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.