Assignment Operators and Augmented Assignment Operators in Kotlin


Definition

  • Assignment Operator is nothing but the "equal to - =" operator. This operator assigns a value to a variable.
  • Augmented Assignment Operators performs operations and assigns the value to the same variable. There are 5 types of Augmented Assignment Operators. They are
    • Addition and Assignment operator (+=)
    • Subtraction and Assignment operator (-=)
    • Multiplication and Assignment operator (*=)
    • Division and Assignment operator (/=)
    • Modulus and Assignment operator (%=)

Syntax

Assignment Operator

var variable_name1 = value

For example,

var number = 5

Addition and Assignment Operator (Augmented Assignment operator)

var variable_name1 += value

For example,

var number += 5

Subtraction and Assignment Operator (Augmented Assignment operator)

var variable_name1 -= value

For example,

var number -= 5

Multiplication and Assignment Operator (Augmented Assignment operator)

var variable_name1 *= value

For example,

var number *= 5

Division and Assignment Operator (Augmented Assignment operator)

var variable_name1 /= value

For example,

var number /= 5

Modulus and Assignment Operator (Augmented Assignment operator)

var variable_name1 %= value

For example,

var number %= 5

Assignment Operators and Augmented Assignment Operator Example Program in Kotlin

//Assignment Operators and Augmented Assignment Operators Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program

fun main(args: Array<String>) {
    val num1 = 100;
    val num2 = 5
    
    //Assigning num1 value to addition variable
    var addition = num1

    //Adding num2 to addition variable and assigning result to the addition variable
    addition += num2
    var subtraction = num1

    //Subtracting num2 from subtraction variable and assigning result to the subtraction variable
    subtraction -= num2
    var multiplication = num1

    //Multiplying num2 and multiplication variables and assigning result to the multiplication variable
    multiplication *= num2
    var division = num1

    //Dividing division by num2 variable and assigning result to the division variable
    division /= num2
    //Modulus of modulus variable by num2 variable and assigning result to the modulus variable
    var modulus = num1
    modulus %= num2

    println("addition and assignment of $num1 and $num2 is : $addition")
    println("subtraction and assignment of $num1 and $num2 is : $subtraction")
    println("multiplication and assignment of $num1 and $num2 is : $multiplication")
    println("division and assignment of $num1 and $num2 is : $division")
    println("modulus and assignment of $num1 and $num2 is : $modulus")
}

Sample Output

addition and assignment of 100 and 5 is : 105
subtraction and assignment of 100 and 5 is : 95
multiplication and assignment of 100 and 5 is : 500
division and assignment of 100 and 5 is : 20
modulus and assignment of 100 and 5 is : 0