Conteúdo do Curso
Introduction to Scala
Introduction to Scala
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.
Main
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.
Main
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.
Main
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.
Main
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.
Main
object Main { def main(args: Array[String]): Unit = { var e = 9 e %= 4 // Equivalent to e = e % 4, e is now 1 println(e) } }
Obrigado pelo seu feedback!