Operators
## Learning Objectives
- Master arithmetic operators
- Understand comparison operators
- Learn logical operators
- Explore operator notation in Scala
## Arithmetic Operators
### Basic Operations
```scala
val a = 10
val b = 3
a + b // 13 (addition)
a - b // 7 (subtraction)
a * b // 30 (multiplication)
a / b // 3 (integer division)
a % b // 1 (modulo/remainder)
```
### Division Behavior
```scala
val intResult = 10 / 3 // 3 (integer division)
val doubleResult = 10.0 / 3.0 // 3.333...
// Type conversion
val result = 10.toDouble / 3 // 3.333...
```
### Numeric Type Operations
```scala
// Int operations
val intMax = Int.MaxValue // 2147483647
val intMin = Int.MinValue // -2147483648
// Overflow example
val overflow = Int.MaxValue + 1 // -2147483648
// BigInt for large numbers
val bigNum = BigInt("12345678901234567890")
val bigResult = bigNum * bigNum
```
## Comparison Operators
### Equality
```scala
val x = 10
val y = 20
val z = 10
x == y // false (structural equality)
x != y // true
// For objects, == calls equals()
val s1 = new String("hello")
val s2 = new String("hello")
s1 == s2 // true (content equality)
s1 eq s2 // false (reference equality)
```
### Relational Operators
```scala
x < y // true
x > y // false
x <= z // true
x >= z // true
// Chaining (Scala 3)
1 < 2 < 3 // true
1 < 2 > 3 // false
```
## Logical Operators
```scala
val a = true
val b = false
!a // false (NOT)
a && b // false (AND)
a || b // true (OR)
```
### Short-circuit Evaluation
```scala
def sideEffect(): Boolean = {
println("Called!")
true
}
false && sideEffect() // false, sideEffect() not called
true || sideEffect() // true, sideEffect() not called
```
## Bitwise Operators
```scala
val x = 5 // 0101 in binary
val y = 3 // 0011 in binary
x & y // 1 (0101 & 0011 = 0001)
x | y // 7 (0101 | 0011 = 0111)
x ^ y // 6 (0105 ^ 0011 = 0110)
~x // -6 (bitwise NOT)
x << 1 // 10 (shift left)
x >> 1 // 2 (shift right, sign-preserving)
x >>> 1 // 2 (shift right, zero-fill)
```
## Operator Notation
### Infix Notation
In Scala, methods can be used as operators:
```scala
// These are equivalent
a.+(b) // Method call
a + b // Operator notation (infix)
// Works with any method
a.+(b) // a + b
a.-(b) // a - b
a.*(b) // a * b
a./(b) // a / b
a.%(b) // a % b
```
### Unary Operators
```scala
val x = 5
+x // 5 (unary +)
-x // -5 (unary -)
!true // false
// Behind the scenes
x.unary_+ // +x
x.unary_- // -x
```
### Precedence Rules
```scala
// Highest to lowest precedence
// *, /, %
// +, -
// <, >, <=, >=
// ==, !=
// &
// ^
// |
// &&
// ||
// = (assignment)
// :, ::, +:, :+, etc.
// All letters
// All assignment operators
```
## String Operations
```scala
val str = "Hello"
// Concatenation
"Hello" + " " + "World" // "Hello World"
str.concat(" Scala") // "Hello Scala"
// String methods as operators
str.take(5) // "Hello"
str.drop(5) // " Scala"
str.contains("lo") // true
str.startsWith("He") // true
str.endsWith("lo") // true
str.indexOf("lo") // 3
str.replace("H", "J") // "Jello"
str.toLowerCase // "hello"
str.toUpperCase // "HELLO"
str.trim // "Hello"
```
## Assignment Operators
```scala
var x = 10
x += 5 // x = 15
x -= 3 // x = 12
x *= 2 // x = 24
x /= 4 // x = 6
x %= 4 // x = 2
// Cannot chain: x = y = 10 is invalid in Scala
```
## Operator Examples
### Mathematical Expressions
```scala
def quadraticFormula(a: Double, b: Double, c: Double): (Double, Double) = {
val discriminant = b * b - 4 * a * c
if (discriminant < 0) {
throw new Exception("No real roots")
}
val sqrtDisc = Math.sqrt(discriminant)
val root1 = (-b + sqrtDisc) / (2 * a)
val root2 = (-b - sqrtDisc) / (2 * a)
(root1, root2)
}
```
### Logical Conditions
```scala
def isLeapYear(year: Int): Boolean = {
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}
def gradeScore(score: Int): Char = {
if (score >= 90) 'A'
else if (score >= 80) 'B'
else if (score >= 70) 'C'
else if (score >= 60) 'D'
else 'F'
}
```
## Summary
- Arithmetic: `+`, `-`, `*`, `/`, `%`
- Comparison: `==`, `!=`, `<`, `>`, `<=`, `>=`
- Logical: `&&`, `||`, `!`
- Bitwise: `&`, `|`, `^`, `~`, `<<`, `>>`, `>>>`
- Scala treats operators as methods (operator notation)
- Any method can be used in infix notation
- Precedence follows mathematical conventions
- String interpolation and methods provide rich string operations
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →