Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
129: Operator Overloading in Kotlin
You've probably spent a lot of time writing methods like calculateTotal() or addPosition(). They work, but they can get wordy. In Kotlin, when we find ourselves writing methods that behave exactly like mathematical operators, we can use operator overloading. It's essentially a way of telling the compiler: "When you see a + sign between two objects of this class, actually call this specific function."
I'm a big fan of this for domain-specific logic. To show you how it works, let's build a simple Vector2D class. If you've ever done game dev or basic physics, you know that adding two vectors or scaling one by a number is a constant task. Writing v1.add(v2) is fine, but v1 + v2 is just cleaner.
Defining the Vector and the plus operator
First, we'll start with a basic data class. To overload the + operator, we need to implement a function called plus and mark it with the operator keyword. If you forget that keyword, Kotlin will just treat it as a regular function and the + symbol won't work.
data class Vector2D(val x: Double, val y: Double) {
operator fun plus(other: Vector2D): Vector2D {
return Vector2D(this.x + other.x, this.y + other.y)
}
}
fun main() {
val pos1 = Vector2D(10.0, 5.0)
val pos2 = Vector2D(2.0, 3.0)
// This now calls the plus() function under the hood
val result = pos1 + pos2
println(result) // Vector2D(x=12.0, y=8.0)
}
The "Why isn't this compiling?" moment
Now, I want to be able to scale my vector. For example, if I have a direction vector and I want to multiply its length by 2. I'll try to implement a times function to handle the * operator. I'll write it quickly, just like I often do when I'm in a flow state:
// Inside Vector2D
fun times(scalar: Double): Vector2D {
return Vector2D(this.x * scalar, this.y * scalar)
}
When I try to run val scaled = pos1 * 2.0, the compiler screams at me. It tells me that the * operator isn't defined for these types. I've made the classic mistake: I named the function times, but I forgot the operator modifier. In Kotlin, naming a function plus or times isn't enough; the modifier is what actually "hooks" the symbol to the function.
Fixing the scaling logic
Let's fix that and add one more thing. I want to be able to multiply the vector by a scalar regardless of whether the scalar comes first or second (e.g., vector * 2 and 2 * vector). To do the latter, I can define a top-level function or an extension function.
data class Vector2D(val x: Double, val y: Double) {
operator fun plus(other: Vector2D): Vector2D {
return Vector2D(this.x + other.x, this.y + other.y)
}
// Fixed: added the operator keyword
operator fun times(scalar: Double): Vector2D {
return Vector2D(this.x * scalar, this.y * scalar)
}
}
// This allows us to do: 2.0 * vector
operator fun Double.times(vector: Vector2D): Vector2D {
return vector.times(this)
}
fun main() {
val v = Vector2D(1.0, 2.0)
println(v * 3.0) // Vector2D(x=3.0, y=6.0)
println(3.0 * v) // Vector2D(x=3.0, y=6.0)
}
Just a quick word of caution: don't overdo this. If you start overloading the minus operator to mean "delete a user from a database," your teammates will hate you. Only use operator overloading when the symbol's meaning is intuitive and mathematically sound.
📋 Practical Task
Implementing a ComplexNumber Arithmetic Class
In mathematics, complex numbers have a real part and an imaginary part (represented as a + bi). Your task is to create a class that makes working with these numbers feel natural using operator overloading.
Requirements:
- Create a data class
ComplexNumberwith two properties:real(Double) andimaginary(Double). - Overload the
plus (+)operator to add two complex numbers. (The formula is:(a+bi) + (c+di) = (a+c) + (b+d)i). - Overload the
minus (-)operator to subtract two complex numbers. (The formula is:(a+bi) - (c+di) = (a-c) + (b-d)i). - Overload the
times (*)operator to multiply aComplexNumberby aDoublescalar.
Test your implementation in a main function by creating two complex numbers, adding them, subtracting one from the other, and scaling one by a factor of 2.0.
There are no comments for now.