Language Elements

Data Types

Kotlin Classes

Kotlin Operators

Kotlin Null Safety

Extension Functions

Lambda Functions

Object Oriented Kotlin

Data Classes

Coroutines

Collections

Delegation

Lateinit and Lazy Initialization

Kotlin Scope Functions

Kotlin Key Words

Kotlin Example Codes

Kotlin Interview Questions

Operators in Kotlin

Operators in Kotlin are special symbols or keywords that are used to perform operations on variables and values. Like most modern languages, Kotlin supports a wide range of operators including arithmetic, logical, relational, and more. In addition to using built-in operators, Kotlin also allows developers to define custom behavior for operators through operator overloading.

Types of Operators in Kotlin

Common Operator Usage


// Arithmetic
val a = 10
val b = 3
println(a + b)   // 13
println(a % b)   // 1

// Comparison
println(a > b)   // true

// Logical
val isAdult = true
val hasTicket = false
println(isAdult && hasTicket)  // false

// Range
for (i in 1..5) {
    print("$i ")   // Output: 1 2 3 4 5
}

// Elvis operator
val name: String? = null
val result = name ?: "Default"
println(result)  // Output: Default
    

Operator Overloading in Kotlin

Kotlin allows classes to provide custom implementations for operators using specially named member functions marked with the operator keyword. This is known as operator overloading. It improves code readability and allows intuitive use of operators with user-defined types.

Example 1: Overloading '+' for a Vector Class


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

val v1 = Vector(1, 2)
val v2 = Vector(3, 4)
val result = v1 + v2
println(result)  // Output: Vector(x=4, y=6)
    

Example 2: Overloading 'get' and 'set'


class Matrix {
    private val data = Array(3) { IntArray(3) }

    operator fun get(row: Int, col: Int): Int {
        return data[row][col]
    }

    operator fun set(row: Int, col: Int, value: Int) {
        data[row][col] = value
    }
}

val m = Matrix()
m[0, 1] = 5
println(m[0, 1])  // Output: 5
    

Supported Operator Functions

Some examples of operator functions you can overload:

Operators in Kotlin make code more concise and expressive. While most operators behave as expected with built-in types, Kotlin's support for operator overloading allows you to extend this expressiveness to your own classes. Use this feature wisely to improve readability and avoid confusion.




Copyright © by Zafar Yasin. All rights reserved.