Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

1.4 Arithmetic and Operator Overloading

Arithmetic operators in Scala work just as you would expect in Java or C++:

val answer = 8 * 5 + 2

The + - * / % operators do their usual job, as do the bit operators & | ^ >> <<. There is just one surprising aspect: These operators are actually methods. For example,

a + b

is a shorthand for

a.+(b)

Here, + is the name of the method. Scala has no silly prejudice against non-alphanumeric characters in method names. You can define methods with just about any symbols for names. For example, the BigInt class defines a method called /% that returns a pair containing the quotient and remainder of a division.

In general, you can write

a method b

as a shorthand for

a.method(b)

where method is a method with two parameters (one implicit, one explicit). For example, instead of

1.to(10)

you can write

1 to 10

Use whatever you think is easier to read. Beginning Scala programmers tend to stick to the Java syntax, and that is just fine. Of course, even the most hardened Java programmers seem to prefer a + b over a.+(b).

There is one notable difference between Scala and Java or C++. Scala does not have ++ or -- operators. Instead, simply use +=1 or -=1:

counter+=1 // Increments counter—Scala has no ++

Some people wonder if there is any deep reason for Scala’s refusal to provide a ++ operator. (Note that you can’t simply implement a method called ++. Since the Int class is immutable, such a method cannot change an integer value.) The Scala designers decided it wasn’t worth having yet another special rule just to save one keystroke.

You can use the usual mathematical operators with BigInt and BigDecimal objects:

val x: BigInt = 1234567890
x * x * x // Yields 1881676371789154860897069000

That’s much better than Java, where you would have had to call x.multiply(x).multiply(x).

  • + Share This
  • 🔖 Save To Your Account