Language Elements

Data Types

Kotlin Classes

Kotlin Operators

Kotlin Constructors

Kotlin Null Safety

Extension Functions

Lambda Functions

Object Oriented Kotlin

Data Classes

Coroutines

Kotlin Collections

Kotlin Data Structures

Kotlin Algorithms

Delegation

Lateinit and Lazy Initialization

Kotlin Scope Functions

Kotlin Key Words

Kotlin Example Codes

Kotlin Interview Questions

Operators and Operator Overloading in Kotlin

Kotlin provides a rich set of built-in operators and allows operator overloading, making code with custom types concise and natural.

Built-in Operators

Everyday Examples


val a = 15
val b = 4

println(a + b)    // 19
println(a % b)    // 3
println(a in 1..20) // true

val name: String? = null
val display = name ?: "Guest"
println(display)  // Guest

Operator Overloading

Any class can define custom behavior for operators by declaring member or extension functions marked with the operator keyword.

1. Overloading +


data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}

val p1 = Point(1, 2)
val p2 = Point(3, 4)
println(p1 + p2)   // Point(x=4, y=6)

2. Overloading indexing []


class Board {
    private val cells = Array(9) { ' ' }

    operator fun get(index: Int) = cells[index]
    operator fun set(index: Int, value: Char) {
        cells[index] = value
    }
}

val board = Board()
board[0] = 'X'
println(board[0])  // X

3. Overloading invocation ()


class Greeter(val greeting: String) {
    operator fun invoke(name: String) = println("$greeting, $name!")
}

val hi = Greeter("Hi")
hi("Kotlin")   // Hi, Kotlin!

Common Overloadable Operators

OperatorRequired function name
+ - * / %plus, minus, times, div, rem
+= -= etc.plusAssign, minusAssign …
== !=equals (data classes do it automatically)
< > <= >=compareTo
[]get / set
()invoke
in !incontains
..rangeTo

Copyright © by Zafar Yasin. All rights reserved.