Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Kotlin offers seven types of operators. They are:

  • Arithmetic operators
  • Assignment operators
  • Unary operators
  • Logical operators
  • Relational operators
  • Special operators

Using Arithmetic Operators

Arithmetic operators allow you to perform mathematical operations on values.

val add = 9+1
println(add) // prints 10

val subtract = 100 - 50
println(subtract) // prints 50

val multiply = 6 * 3
println(multiply) // prints 18

val divide = 10 / 2
println(divide) // prints 5

val remainder = 11 % 2
println(remainder) // prints 1

Using Assignment Operators

Assignment operators let you assign values to variables. = is the simplest assignment operator that allows you to assign a value, as shown below:

val a = 5
var a = 5
a += 2 // equivalent to a = a + 2
println(a) // prints 7

var b = 10
b /= 2 // equivalent to b = b / 2
println(b) // prints 5

Using Unary Operators

Unary operators perform operations on a single operand. Kotlin offers two unary operators:

var a = 3
a++ // equivalent to a = a + 1
println(a) // prints 4

var b = 10
b-- //equivalent to b = b -1
println(b) // prints 9

Using Logical Operators

Logical operators allow you to perform logical operations. These operations have a Boolean result, true or false. Kotlin offers three logical operators:


// Logical AND (&&)
val number = 20 
val isEvenMultipleOfFive = number % 2 == 0 && number % 5 == 0 
println("$number is both even and a multiple of 5: $isEvenMultipleOfFive") //prints true

//Logical OR (||)
val raining = true
val temperature = 35

val carryUmbrella = raining || temperature > 30
println("Carry an umbrella: $carryUmbrella") // prints true

//Logical NOT
val isTrue = true
println(!isTrue) // prints false

Using Relational Operators

Relational operators allow you to compare two values, giving you a Boolean result. The relational operators offered by Kotlin are:

var a = 5
var b = 5
println(a == b) // prints true

a = 9
b = 10
println(a != b) // prints true
println(a < b) // prints true
println(a > b) // prints false

a = 25
println (a >= 25) // prints true
println (a <= 25) // prints true

Using Special Operators

In addition to the operators mentioned earlier, Kotlin offers two special operators:

var nullableMessage: String? = null
val result = nullableMessage ?: "variable is null"
println(result) // prints "variable is null"

val length = nullableMessage?.length
println(length) //prints null
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo