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

Kotlin Subtraction

Kotlin Subtraction Operator takes two operands as inputs and returns the difference of second operand from the first operand.

- symbol is used for Subtraction Operator.

Syntax

The syntax for Subtraction Operator is

</>
Copy
operand_1 - operand_2

The operands could be of any numeric datatype.

If the two operands are of different datatypes, implicit datatype promotion takes place and value of lower datatype is promoted to higher datatype.

Examples

1. Subtraction of two integers

In the following example, we take two integers: a and b, and find the difference a - b, using Subtraction Operator.

Main.kt

</>
Copy
fun main() {
    var a = 30
    var b = 10
    var diff = a - b
    println("Difference : $diff")
}

Output

Difference : 20

2. Subtraction of different datatype values

In the following example, we shall find the difference of an integer from a Float number using Subtraction Operator.

As we are finding the difference of two different datatype values, one with lower datatype promotes to higher datatype and the result is of higher datatype. In the following example, Int would be promoted to Float, and the result would be Float.

Main.kt

</>
Copy
fun main() {
    var a = 30.524
    var b = 10
    var diff = a - b
    println("Difference : $diff")
}

Output

Difference : 20.524

Conclusion

In this Kotlin Tutorial, we learned how to use Subtraction Operator to find the difference between two numbers.