In this tutorial, you shall learn about Decrement operator in Kotlin, its syntax, and how to use Decrement operator in programs, with examples.

Kotlin Decrement

Kotlin Decrement Operator takes a variable as operand and decreases the value in variable by one.

-- symbol is used for Decrement Operator.

There are two types of decrement operations based on the position of operand for the operator.

  1. Pre-decrement
  2. Post-decrement

Syntax

The syntax for Decrement Operator is

</>
Copy
//pre-decrement
--operand

//post-decrement
operand--

The operands could be of any numeric datatype.

For Pre-decrement operation, first the value in the variable is decreased by one, and then the value is substituted in the expression or current statement.

For Post-decrement operation, first the current statement is executed, and then the value in the variable is decremented.

Examples

1. Decrement a variable

In the following example, we take an integer value in a, and decrement its value by one using Decrement Operator.

Main.kt

</>
Copy
fun main() {
    var a = 5
    a--
    println("a : $a")
}

Output

a : 4

2. Decrement a decimal value

In the following example, we take a decimal value in a, and decrement its value by one using Decrement Operator.

Main.kt

</>
Copy
fun main() {
    var a = 5.748
    a--
    println("a : $a")
}

Output

a : 4.748

3. Pre-decrement

In the previous examples, we have seen post-decrement operation. But in this example, we will see how a pre-decrement operation works.

In the following example, we take an integer value in a, and pre-decrement its value using Decrement Operator.

Main.kt

</>
Copy
fun main() {
    var a = 5
    var result = --a * 4
    println("a : $result")
}

Output

a : 16

The value in a is decremented by 1, and then that value of a is substituted in the expression.

Now, let us take the same example, but with post-decrement operation.

Main.kt

</>
Copy
fun main() {
    var a = 5
    var result = a-- * 4
    println("a : $result")
}

Output

a : 20

First the expression a * 4 is evaluated, and then the decrement of a happens. If you print the value of a after the third line, then you would observe that the value in a is decremented.

Conclusion

In this Kotlin Tutorial, we learned how to use Decrement Operator to decrease the value in a variable by one.