Scala operators are symbols or keywords that perform specific operations on one or more operands. They are essential for manipulating data and controlling program flow in Scala applications.
Arithmetic operators perform mathematical calculations on numeric values.
+
(addition)-
(subtraction)*
(multiplication)/
(division)%
(modulus)Example:
val a = 10
val b = 3
println(a + b) // Output: 13
println(a - b) // Output: 7
println(a * b) // Output: 30
println(a / b) // Output: 3
println(a % b) // Output: 1
Comparison operators compare two values and return a boolean result.
==
(equal to)!=
(not equal to)>
(greater than)<
(less than)>=
(greater than or equal to)<=
(less than or equal to)Example:
val x = 5
val y = 7
println(x == y) // Output: false
println(x != y) // Output: true
println(x > y) // Output: false
println(x < y) // Output: true
Logical operators perform boolean operations on boolean values.
&&
(logical AND)||
(logical OR)!
(logical NOT)Example:
val p = true
val q = false
println(p && q) // Output: false
println(p || q) // Output: true
println(!p) // Output: false
Bitwise operators perform operations on individual bits of integer values.
&
(bitwise AND)|
(bitwise OR)^
(bitwise XOR)~
(bitwise NOT)<<
(left shift)>>
(right shift)>>>
(unsigned right shift)Example:
val m = 5 // Binary: 0101
val n = 3 // Binary: 0011
println(m & n) // Output: 1 (Binary: 0001)
println(m | n) // Output: 7 (Binary: 0111)
println(m ^ n) // Output: 6 (Binary: 0110)
println(m << 1) // Output: 10 (Binary: 1010)
Scala follows a specific order of precedence for operators. When multiple operators are used in an expression, the operators with higher precedence are evaluated first.
Here's a simplified precedence order (from highest to lowest):
()
+
, -
, !
, ~
)*
, /
, %
)+
, -
)<<
, >>
, >>>
)<
, >
, <=
, >=
)==
, !=
)&
^
|
&&
||
Scala allows you to define custom operators using symbols. This feature enables the creation of domain-specific languages (DSLs) and more expressive code.
Example of a custom operator:
class Vector(val x: Int, val y: Int) {
def +(other: Vector) = new Vector(x + other.x, y + other.y)
}
val v1 = new Vector(1, 2)
val v2 = new Vector(3, 4)
val v3 = v1 + v2
println(s"Result: (${v3.x}, ${v3.y})") // Output: Result: (4, 6)
Understanding Scala operators is crucial for writing efficient and expressive code. They form the foundation for more advanced concepts like Scala Expressions and Scala Function Basics. As you progress in your Scala journey, you'll find these operators essential in various programming tasks.