2.4. Replacements for ++ and −−
Problem
You want to increment or decrement numbers using operators like
++
and −−
that are available in other languages, but
Scala doesn’t have these operators.
Solution
Because val
fields are
immutable, they can’t be incremented or decremented, but var Int
fields can be mutated with the
+=
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 ^
Note
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.
Discussion
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: ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.