There are no ++ or -- operators in Scala (use += or -=)

In Scala there are no ++ or -- operators. You should instead use the += and -= operators, as shown below. First the += operator:

scala> var i = 1
i: Int = 1

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

scala> i += 1

scala> println(i)
2

Next the -= operator:

scala> i--
<console>:9: error: value -- is not a member of Int
              i--
               ^

scala> i -= 1

scala> println(i)
1

From what I've read, there are two reasons that there are no ++ or -- operators in Scala. First, in regards to "language purity", allowing for them would have meant adding a special rule to the language, and the language designers wanted to avoid that. Second, Scala encourages the use of immutable values, and with immutable values you'll have no need for these operators.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.