Assignment Operators

In the following lesson, you will be introduced to assignment operators.

Assignment operators are used for performing operations which assign a value to an operand. They are modified versions of all the operators we have discussed so far.

Let’s look at the arithmetic assignment operators supported by Scala.

Operator Use
+= Adds two operands and assigns the result to the left operand
-= Subtracts the second operand from the first and assigns the result to the left operand
*= Multiplies both operands and assigns the result to the left operand
/= Divides the first operand by the second operand and assigns the result to the left operand
%= Finds the remainder after division of one number by another and assigns the result to the left operand

You might have noticed a pattern. Assignment operators require variable type operands as the result of the operation is assigned to the left/first operand.

In our example, we will take the left operand A to be 10 and the right operand B to be 7.

Remember to declare mutable variables using the keyword var as they have to be reassigned using the assignment operator.

Press + to interact
var A = 10
var B = 7
print("Before using an assignment operator: ")
println(A)
A += B
print("After using an assignment operator: ")
println(A)

Before reassigning the variable A, its value was 10. After using the assignment operator +=, its new value is 17. Try the above code with different assignment operators and see what you get.


And with assignment operators, our types of operators come to an end. In the next lesson, you will be challenged to use what you’ve learned about operators.