</>
Skip to content
Kotlin lessons (9/33)

Kotlin — Operators

Arithmetic operators

fun main() {
    val a = 10
    val b = 3

    println("Add: ${a + b}")   // 13
    println("Sub: ${a - b}")   // 7
    println("Mul: ${a * b}")   // 30
    println("Div: ${a / b}")   // 3
    println("Mod: ${a % b}")   // 1
}

Comparison operators

fun main() {
    println(5 == 5)  // true
    println(5 != 3)  // true
    println(5 > 3)   // true
    println(5 < 3)   // false
    println(5 >= 5)  // true
    println(5 <= 3)  // false
}

Logical operators

fun main() {
    val a = true
    val b = false

    println(a && b)  // false (AND)
    println(a || b)  // true  (OR)
    println(!a)      // false (NOT)
}

Range operator

fun main() {
    // .. operator
    for (i in 1..5) {
        print("$i ")
    }
    println() // 1 2 3 4 5

    // in operator
    println(3 in 1..5)   // true
    println(6 in 1..5)   // false

    // downTo
    for (i in 5 downTo 1) {
        print("$i ")
    }
    println() // 5 4 3 2 1

    // step
    for (i in 1..10 step 2) {
        print("$i ")
    }
    println() // 1 3 5 7 9
}

Elvis operator

fun main() {
    val name: String? = null
    val length = name?.length ?: 0
    println(length) // 0
}

Safe and not-null operators

fun main() {
    val name: String? = "Alice"

    // Safe call
    println(name?.length) // 5

    // Not-null assertion (careful!)
    // println(name!!.length) // Throws if null
}

Mini Practice

Write Kotlin code that:

  1. Demonstrates all arithmetic operators
  2. Uses the range operator with step
  3. Uses the Elvis operator for defaults
  4. Shows safe call operator usage

Up Next

In the next lesson, you'll learn about Strings — working with text in Kotlin.

Related Topics

Frequently Asked Questions about Operators

What is Operators in Kotlin?

Operators is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Operators?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Operators.

Why is Operators important in Kotlin?

Operators is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.