Operators

An operator is a symbol which has special meaning and performs an operation on single or multiple operands like addition, substraction etc. Scala provides rich set of in-built operators.

Types of Operators in Scala

1. Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on operands.

OperatorDescriptionExample
+Used to perform Addition8+2 = 10
-Used to perform Subtraction12-2 = 10
*Used to perform Multiplication5*2 = 10
/Used to perform Division and returns float values10/3 = 3.3333
%Used to return Remainder40%10 = 0

2. Comparison Operators

Comparison operators are used to compare two operands.

OperatorDescriptionUsage
==Is equal tox == y
!=Not equal to!=x
>Greater thanx > y
>=Greater than or equal tox >= y
<Less thanx < y
<=Less than or equal tox <= y

3. Bitwise Operators

Bitwise operators are used to perform bitwise operations on operands.

OperatorDescriptionUsage
&Bitwise AND(x > y) & (y > z)
|Bitwise OR(x > y) | (y > z)
^Bitwise XOR(x > y) ^ (y > z)
~Bitwise NOT(~x)
<<Bitwise Left Shiftx << y
>>Bitwise Right Shiftx >> y
>>>Shift right zero fill operatorx >>> y

4. Logical Operators

Logical operators are as shown below:

OperatorDescriptionUsage
&&Logical AND(x > y) && (y > z)
||Logical OR(x > y) || (y > z)
!Logical NOT(!x)

5. Assignment Operators

Assignment operators are as shown below:

OperatorDescriptionUsage
=Assignx = 10;
+=Add and assignx=10; x+=30; //x becomes 40
-=Subtract and assignx=40; x-=10; //x becomes 30
*=Multiply and assignx=10; x*=40; //x becomes 400
/=Divide and assignx=100; x /= 10; //x becomes 10
%=Modulus and assignx=100; x%=10; //x becomes 0
<<=Bitwise Left Shift and assignx <<= 2; // x = x << 2
>>=Bitwise Right Shift and assignx >>= 2; // x = x >> 2
&=Bitwise AND and assignx &= y; // x = x & y
|=Bitwise OR and assignx |= y; // x = x | y
^=Bitwise XOR and assignx ^= y; // x = x ^ y

Summary

TypeOperators
Arithmetic Operators+ , - , * , / , %
Comparision Operators== , != , > , >= , < , <=
Bitwise Operators& , ^ , | , ^ , ~ , << , >> , >>>
Logical Operators&& , || , !
Assignment Operators= , += , -= , *= , /= , %= , &= , ^= , |= , <<= , >>=