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
You need to compare two floating-point numbers, but as in some other programming languages, two floating-point numbers that should be equivalent may not be.
Solution
As in Java and many other languages, you solve this problem by creating a method that lets you specify the precision for your comparison. The following “approximately equals” method demonstrates the approach: