Lesson Overview

Welcome to the newest chapter of our journey through Scala: arithmetic and logical operations. These operations are the cornerstone of programming, facilitating calculations and decision-making. Let's dive right in!

Importance of Arithmetic Operations in Scala

Arithmetic operations in Scala include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). The modulus operation, %, calculates the remainder after dividing one number by another. For instance, 7 % 3 equals 1, because 7 divided by 3 leaves a remainder of 1. We'll explore these operations through examples using variables a and b:

@main def run: Unit =
  val a = 10
  val b = 2

  println(a + b)  // prints: 12
  println(a - b)  // prints: 8
  println(a * b)  // prints: 20
  println(a / b)  // prints: 5
  println(a % b)  // prints 0, because the remainder of 10/2 is 0
Compound Assignment Operators

Scala offers a means to streamline arithmetic operations combined with assignment through the use of compound assignment operators. These operators, which include +=, -=, *=, /=, and %=, combine an arithmetic operation with an assignment to enhance code readability.

@main def run: Unit =
  var score = 100
  score += 10   // same as `score = score + 10`, score is now 110
  score -= 20   // same as `score = score - 20`, score is now 90
  score *= 2    // same as `score = score * 2`, score is now 180
  score /= 3    // same as `score = score / 3`, score is now 60
  score %= 7    // same as `score = score % 7`, score is now 4
Understanding Logic in Scala

Logical operations, specifically AND (&&), OR (||), and NOT (!), are indispensable for making branching decisions in Scala. AND (&&) returns true only if both operands are true. OR (||) returns true if either operand is true. NOT (!) inverts the boolean value. Here is an example of an in-game task:

@main def run: Unit =
  val hasEnoughPoints = true
  val hasEnoughCoins = false

  println(hasEnoughPoints && hasEnoughCoins)  // prints: false
  println(hasEnoughPoints || hasEnoughCoins)  // prints: true
  println(!hasEnoughCoins)                    // prints: true
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal