Scala has no ++ or -- operator; how to increment or decrement an integer?

Scala FAQ: Scala doesn't have the ++ and -- operators; are the some similar operators or methods that I can use instead?

Solution

Because val fields in Scala are immutable, they can’t be incremented or decremented, but var integer fields can be mutated with Scala’s += and −= methods:

scala> var a = 1
a: Int = 1

scala> a += 1

scala> println(a)
2

scala> a −= 1

scala> println(a)
1

As an added benefit, you use similar methods for multiplication and division:

scala> var i = 1
i: Int = 1

scala> i *= 2

scala> println(i)
2

scala> i *= 2

scala> println(i)
4

scala> i /= 2

scala> println(i)
2

Note that these symbols aren’t operators; they’re implemented as methods that are available on Int fields declared as a var. Attempting to use them on val fields results in a compile-time error:

scala> val x = 1
x: Int = 1

scala> x += 1
<console>:9: error: value += is not a member of Int
              x += 1
                ^

Discussion

As mentioned, the symbols +=, −=, *=, and /= aren’t operators, they’re methods. This approach of building functionality with libraries instead of operators is a consistent pattern in Scala. Actors, for instance, are not built into the language, but are instead implemented as a library. See the Dr. Dobbs’ link in the See Also for Martin Odersky’s discussion of this philosophy.

Another benefit of this approach is that you can call methods of the same name on other types besides Int. For instance, the Double and Float classes have methods of the same name:

scala> var x = 1d
x: Double = 1.0

scala> x += 1

scala> println(x)
2.0

scala> var x = 1f
x: Float = 1.0

scala> x += 1

scala> println(x)
2.0

See Also

  • Martin Odersky discusses how Actors are added into Scala as a library on drdobbs.com.