Why no i++ in Scala?

前端 未结 11 1887
半阙折子戏
半阙折子戏 2020-12-23 10:48

I just wonder why there is no i++ to increase a number. As what I know, languages like Ruby or Python doesn\'t support it because they are dynamically typed. So

11条回答
  •  旧巷少年郎
    2020-12-23 11:46

    Rafe's answer is true about the rationale for why something like i++ doesn't belong in Scala. However I have one nitpick. It's actually not possible to implement i++ in Scala without changing the language.

    In Scala, ++ is a valid method, and no method implies assignment. Only = can do that.

    Languages like C++ and Java treat ++ specially to mean both increment and assign. Scala treats = specially, and in an inconsistent way.

    In Scala when you write i += 1 the compiler first looks for a method called += on the Int. It's not there so next it does it's magic on = and tries to compile the line as if it read i = i + 1. If you write i++ then Scala will call the method ++ on i and assign the result to... nothing. Because only = means assignment. You could write i ++= 1 but that kind of defeats the purpose.

    The fact that Scala supports method names like += is already controversial and some people think it's operator overloading. They could have added special behavior for ++ but then it would no longer be a valid method name (like =) and it would be one more thing to remember.

提交回复
热议问题