Operators
In a Computer Everything is a Number.
Strings, Images, Audio, Video are All Encoded as Numbers.
Scala does have some operators to do the basic calculations.
But with these basic thing you can do everything
- toUpperCase on a text
- darken an image
- lower the volume on audio
- calculate the average on a dataset
Arithmetic operators
val a = 5
val b = 2
val sum = a + b // Addition operator
val difference = a - b // Subtraction operator
val product = a * b // Multiplication operator
val quotient = a / b // Division operator
val remainder = a % b // Modulus operator
| operator | function |
|---|---|
| + | add |
| - | subtract |
| * | multiply |
| / | divide |
| % | modulo |
Examples
scala>
val a: Int = 4
val b: Int = 3
scala> val add = a + b
val add: Int = 7
scala> val subtract = a - b
val subtract: Int = 1
scala> val multiply = a * b
val multiply: Int = 12
scala> val divide = a / b
val divide: Int = 1
This is an integer division. So it will give an integer value.
modulo
Modulo is the rest of an integer division
scala> val modulo = a % b
val modulo: Int = 1
divide floating point
If you want a floating point division then you have to cast an Int to a Double
scala> val d: Double = a / b
val d: Double = 1.0
To change to type to a Double is no enough, also a typecast is needed: toDouble
scala> val d: Double = a / b.toDouble
val d: Double = 1.3333333333333333
Comparison operators
| operator | function |
|---|---|
| > | greater then |
| < | smaller then |
| == | equals |
| >= | greater and equals |
| <= | smaller and equals |
val x = 10
val y = 5
val isGreaterThan = x > y // Greater than operator
val isLessThan = x < y // Less than operator
val isEqualTo = x == y // Equality operator
val isNotEqualTo = x != y // Inequality operator
scala> b < 4
val res0: Boolean = true
scala> b > 4
val res1: Boolean = false
scala> b == 3
val res2: Boolean = true
scala> b >= 4
val res3: Boolean = false
scala> b <= 4
val res4: Boolean = true
Logical operators
| operator | function |
|---|---|
| && | AND |
| || | OR |
| ! | NOT |
val p = true
val q = false
val andResult = p && q // Logical AND operator
val orResult = p || q // Logical OR operator
val notResult = !p // Logical NOT operator
scala> b != 4
val res5: Boolean = true
scala> b > 2 && b < 4
val res6: Boolean = true
scala> b < 2 || b > 4
val res7: Boolean = false