Replacements for ++ and -- in Scala (increment or decrement an integer)

In this tutorial, we will learn about the replacements for ++ and -- operators in Scala with examples. By Shivang Yadav Last updated : April 02, 2023

Scala has no ++ or -- operator, how to increment or decrement an integer?

The Scala programming language doesn't support unary operators (++ or --). In Scala, the binary operators are used to increment and decrement an integer.

Common binary operators for increasing and decreasing an integer, we use the increase and assign or decrease and assign operator.

  1. Increase and assignment operator : +=
  2. Decrease and assignment operator : -=

Scala example of increment or decrement an integer

object myClass {
  def main(args: Array[String]): Unit = {
    var a = 45;
    println("initial value of a " + a)
    
    // incrementing the value
    a += 1
    println("incremented value of a " + a)
    
    // decreasnig the value
    var b = 78
    println("initial value of b " + b)
    
    b -= 1
    println("decremented value of b " + b)
  }
}

Output

initial value of a 45
incremented value of a 46
initial value of b 78
decremented value of b 77




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.