Why no i++ in Scala?

前端 未结 11 1877
半阙折子戏
半阙折子戏 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:53

    Scala is perfectly capable of parsing i++ and, with a small modification to the language, could be made to modify a variable. But there are a variety of reasons not to.

    First, it saves only one character, i++ vs. i+=1, which is not very much savings for adding a new language feature.

    Second, the ++ operator is widely used in the collections library, where xs ++ ys takes collection xs and ys and produces a new collection that contains both.

    Third, Scala tries to encourage you, without forcing you, to write code in a functional way. i++ is a mutable operation, so it's inconsistent with the idea of Scala to make it especially easy. (Likewise with a language feature that would allow ++ to mutate a variable.)

提交回复
热议问题