Increment (++) operator in Scala

Viewed 55025

Is there any reason for Scala not support the ++ operator to increment primitive types by default? For example, you can not write:

var i=0
i++

Thanks

9 Answers

Of course you can have that in Scala, if you really want:

import scalaz._
import Scalaz._

case class IncLens[S,N](lens: Lens[S,N], num : Numeric[N]) { 
  def ++ = lens.mods(num.plus(_, num.one))
}

implicit def incLens[S,N:Numeric](lens: Lens[S,N]) =
  IncLens[S,N](lens, implicitly[Numeric[N]])

val i = Lens[Int,Int](identity, (x, y) => y)

val imperativeProgram = for {
  _ <- i := 0;
  _ <- i++;
  _ <- i++;
  x <- i++
} yield x

def runProgram = imperativeProgram ! 0

And here you go:

scala> runProgram
runProgram: Int = 3
Related