Learn Scala 3 Fast: Constructs: Mathematical Expressions

Now that you’ve seen Scala’s data types, we can look at mathematical expressions. In this area, Scala is very much like other programming languages. These examples show the math operations on Int values:

val a = 1
val b = a + 10    // 11
val c = b * 2     // 22
val d = c - 2     // 20
val e = d / 2     // 10
val f = e % 3     // 1 (modulus operator)

As shown, those are the symbols you use for addition, multiplication, subtraction, division, and the modulus operation.

In that example I use different names for each variable because, as mentioned, val fields are like algebraic variables and cannot vary. If you prefer to use just one variable in situations like this, this is a place where you use a var, which can be reassigned to hold new values:

var a = 1     // note that 'a' is now a 'var'

a = a + 10    // 11
a = a * 2     // 22
a = a - 2     // 20
a = a / 2     // 10
a = a % 3     // 1 (modulus operator)

Scala does not have the ++ and -- operators that you see with some other programming languages, but when you need to increment or decrement a number you do it with the += and -= operators, like this:

var a = 1

a += 1    // a == 2
a -= 1    // a == 1

While this might seem a little less convenient, a nice thing about this is that the same approach works with Double values and other numeric data types:

var a = 10.0    // a Double

a += 1.5        // 11.5
a -= 3.0        // 8.5

You’ll see this sort of thoughtful consistency throughout the Scala language.

A note about these “operators”

For the sake of simplicity I refer to these mathematical symbols as operators, but they’re actually methods. That is, symbols like +, -, etc., that look like operators are really methods on the numeric data type classes. If you’re not familiar with OOP and classes this will make more sense later in this book, but for now, just know that this is evidence of Scala being a true object-oriented programming language.

Exercises

The exercises for this lesson are available here.

books by alvin