Sunday, 23 October 2016

Learn more on Scala Types : Replacements for ++ and −− : Day 3 Learnings

Replacements for ++ and −−

You want to increment or decrement numbers using operators like ++ and −− that are 
available in other languages, but Scala doesn’t have these operators.

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.


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


Share this article with your friends.
Related Posts Plugin for WordPress, Blogger...