Kotlin is a modern language that is widely used in Android development and can be easily utilized for server-side applications due to its concise syntax and safety features. In this article, we will explore how you can perform basic arithmetic operations in Kotlin.

Addition

Addition in Kotlin can be performed using the + operator. You can add numbers or even concatenate strings using the same operator.

fun main() {
    val a = 5
    val b = 10
    val sum = a + b
    println("Sum: $sum") // Output: Sum: 15

    val string1 = "Hello, "
    val string2 = "World!"
    val greeting = string1 + string2
    println(greeting) // Output: Hello, World!
}

Subtraction

For subtraction, you use the - operator. This works similarly to addition.

fun main() {
    val a = 10
    val b = 3
    val difference = a - b
    println("Difference: $difference") // Output: Difference: 7
}

Multiplication

The * operator is used for multiplication in Kotlin.

fun main() {
    val a = 7
    val b = 6
    val product = a * b
    println("Product: $product") // Output: Product: 42
}

Division

Division can be done using the / operator. It is important to note how integer division behaves versus floating-point division.

fun main() {
    val a = 9
    val b = 2
    val integerDivision = a / b
    println("Integer Division: $integerDivision") // Output: Integer Division: 4

    val floatA = 9.0
    val floatB = 2.0
    val floatDivision = floatA / floatB
    println("Float Division: $floatDivision") // Output: Float Division: 4.5
}

Modulus

The modulus operator % is used to get the remainder of a division.

fun main() {
    val a = 13
    val b = 5
    val remainder = a % b
    println("Remainder: $remainder") // Output: Remainder: 3
}

Compound Assignment Operators

Kotlin supports compound assignment operators to simplify arithmetic operations, such as +=, -=, *=, /=, and %=.

fun main() {
    var number = 10
    number += 5 // Equivalent to: number = number + 5
    println(number) // Output: 15

    number -= 3 // Equivalent to: number = number - 3
    println(number) // Output: 12

    number *= 2 // Equivalent to: number = number * 2
    println(number) // Output: 24

    number /= 4 // Equivalent to: number = number / 4
    println(number) // Output: 6

    number %= 4 // Equivalent to: number = number % 4
    println(number) // Output: 2
}

Arithmetic operations in Kotlin are straightforward due to the language's clean syntax. By understanding these operations and their compound counterparts, you can perform a wide range of tasks efficiently.