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
- Arithmetic Operators: +, -, *, /, %
- Assignment Operators: =, +=, -=, *=, /=, %=
- Comparison Operators: ==, !=, <, >, <=, >=
- Logical Operators: &&, ||, !
- Bitwise Operators: shl, shr, ushr, and, or, xor, inv
- Range and Progression Operators: .., until, downTo, step
- In and Not In: in, !in
- Identity Checks: ===, !==
- Null Safety Operators: ?. (safe call), ?: (elvis), !! (not-null assertion)
- Function and Index Access: invoke(), get(), set()
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:
plus,minus,times,div,remunaryMinus,unaryPlus,notequals,compareTo,containsget,set,invoke,iterator
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.