Why no i++ in Scala?

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

    The question to ask is why there should be such an operator, not why there shouldn't be. Would Scala be improved by it?

    The ++ operator is single-purpose, and having an operator that can change the value of a variable can cause problems. It's easy to write confusing expressions, and even if the language defines what i = i + i++ means, for example, that's a lot of detailed rules to remember.

    Your reasoning on Python and Ruby is wrong, by the way. In Perl, you can write $i++ or ++$i just fine. If $i turns out to be something that can't be incremented, you get a run-time error. It isn't in Python or Ruby because the language designers didn't think it was a good idea, not because they're dynamically typed like Perl.

提交回复
热议问题