Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Assignment Operators | Variables and Data Types
Introduction to Scala
course content

Зміст курсу

Introduction to Scala

Introduction to Scala

1. Getting Started
2. Variables and Data Types
3. Conditional Statements and Loops
4. Arrays
5. Strings

Assignment Operators

In Scala, assignment operators are used to assign values to variables. Understanding these operators is crucial for manipulating data in a Scala program effectively.

Compound Assignment Operators

We have already used the basic assignment operator = which simply assigns the value on the right side of the operator to the variable on the left side.

However, Scala also supports compound assignment operators.

Addition Assignment

The addition assignment operator += simply adds the right operand to the left operand and assigns the result to the left operand.

java

Main

copy
12345678
object Main { def main(args: Array[String]): Unit = { var a = 5 println(a) a += 3 // Equivalent to a = a + 3, a is now 8 println(a) } }

Subtraction Assignment

The subtraction assignment operator -= works in the same way as the addition operators performing subtraction and assignment.

java

Main

copy
1234567
object Main { def main(args: Array[String]): Unit = { var b = 10 b -= 4 // Equivalent to b = b - 4, b is now 6 println(b) } }

Multiplication Assignment

The multiplication assignment operator *= works in the same way as the previous operators performing multiplication and assignment.

java

Main

copy
1234567
object Main { def main(args: Array[String]): Unit = { var c = 6 c *= 2 // Equivalent to c = c * 2, c is now 12 println(c) } }

Division Assignment

The division assignment operator /= works in the same way as the previous operators performing division and assignment.

java

Main

copy
1234567
object Main { def main(args: Array[String]): Unit = { var d = 20 d /= 4 // Equivalent to d = d / 4, d is now 5 println(d) } }

Modulus Assignment

The modulus assignment operator %= works in the same way as the previous operators performing the modulus operation (finding the remainder) and assignment.

java

Main

copy
1234567
object Main { def main(args: Array[String]): Unit = { var e = 9 e %= 4 // Equivalent to e = e % 4, e is now 1 println(e) } }

Select the final value of the result variable.

Виберіть правильну відповідь

Все було зрозуміло?

Секція 2. Розділ 8
We're sorry to hear that something went wrong. What happened?
some-alt