Scala FAQ: Scala doesn't have the
-- operators; are the some similar operators or methods that I can use instead?
val fields are immutable, they can’t be incremented or decremented, but
var integer fields can be mutated with Scala’s
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 ^
As mentioned, the symbols
/= 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
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
- Martin Odersky discusses how Actors are added into Scala as a library on drdobbs.com.
The Scala Cookbook
This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:
You can find the Scala Cookbook at these locations: