Operators in Scala

Operators in Scala

Here is a table listing some of the commonly used operators in Scala, categorized by type:

CategoryOperatorDescriptionExample
Arithmetic+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division6 / 2 = 3
%Modulus (Remainder)7 % 3 = 1
Relational==Equal to5 == 5 // true
!=Not equal to5 != 3 // true
>Greater than5 > 3 // true
<Less than3 < 5 // true
>=Greater than or equal to5 >= 5 // true
<=Less than or equal to3 <= 5 // true
Logical&&Logical AND(true && false) // false
``
!Logical NOT!true // false
Bitwise&Bitwise AND5 & 3 = 1
``Bitwise OR
^Bitwise XOR5 ^ 3 = 6
~Bitwise NOT~5 = -6
<<Left shift5 << 1 = 10
>>Right shift (signed)5 >> 1 = 2
>>>Right shift (unsigned)5 >>> 1 = 2
Assignment=Simple assignmentvar x = 5
+=Add and assignx += 3 // x = x + 3
-=Subtract and assignx -= 3 // x = x - 3
*=Multiply and assignx *= 3 // x = x * 3
/=Divide and assignx /= 3 // x = x / 3
%=Modulus and assignx %= 3 // x = x % 3
Concatenation+String concatenation"Hello" + " World"
TypeisInstanceOfCheck if an object is of a specific typex.isInstanceOf[String]
asInstanceOfCast an object to a specific typex.asInstanceOf[String]
Pattern MatchingmatchPattern matching (similar to switch-case in other languages)x match { case 1 => ... }
Other::Prepend element to list1 :: List(2, 3) // List(1, 2, 3)
:::Concatenate two listsList(1, 2) ::: List(3, 4)
->Creates a tuple (key-value pair)1 -> "One" // (1, "One")
==>Used in maps for key-value mappingMap(1 ==> "One")
Function CallapplyImplicitly used to call an object like a functionlist(0) == list.apply(0)

Notes:

  • Operators in Scala are just methods: In Scala, operators are methods. For example, 5 + 3 is actually 5.+(3). This allows for operator overloading and the creation of custom operators.
  • Precedence: Operator precedence in Scala is determined by the first character of the operator.