Why no i++ in Scala?

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

    You could simulate it, though. As a trivial example:

    scala> case class IncInt(var self: Int = 0) { def ++ { self += 1 } }
    defined class IncInt
    
    scala> val i = IncInt()
    i: IncInt = IncInt(0)
    
    scala> i++
    
    scala> i++
    
    scala> i
    res28: IncInt = IncInt(2)
    

    Add some implicit conversions and you're good to go. However, this sort of changes the question into: why isn't there a mutable RichInt with this functionality?

提交回复
热议问题