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

旧时模样 提交于 2019-11-29 22:49:08
Owen

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

tolitius

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

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

thomasrutter

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!