Challenge - 5 Problems
Kotlin Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin code using operator functions?
Consider this Kotlin code where operators are used as functions. What will be printed?
Kotlin
data class Point(val x: Int, val y: Int) { operator fun plus(other: Point) = Point(x + other.x, y + other.y) } fun main() { val p1 = Point(1, 2) val p2 = Point(3, 4) val p3 = p1 + p2 println("(${p3.x}, ${p3.y})") }
Attempts:
2 left
💡 Hint
Remember that the plus operator calls the plus() function defined in the class.
✗ Incorrect
In Kotlin, operators like + are actually functions. Here, plus() adds the x and y values of two Points. So (1+3, 2+4) = (4, 6).
🧠 Conceptual
intermediate1:30remaining
Why does Kotlin treat operators as functions?
Why does Kotlin design operators like +, -, * as functions instead of special syntax?
Attempts:
2 left
💡 Hint
Think about how you can add two custom objects using + in Kotlin.
✗ Incorrect
Kotlin treats operators as functions so you can define how operators behave on your own classes, making code more expressive and flexible.
🔧 Debug
advanced2:00remaining
What error does this Kotlin code produce?
This Kotlin code tries to use the minus operator on a class without defining minus(). What error occurs?
Kotlin
class Counter(val count: Int) fun main() { val c1 = Counter(5) val c2 = Counter(3) val c3 = c1 - c2 println(c3.count) }
Attempts:
2 left
💡 Hint
Check if the minus operator function is defined for the class.
✗ Incorrect
Since Counter does not define operator fun minus, Kotlin cannot apply '-' to Counter objects, causing a compile error.
📝 Syntax
advanced1:30remaining
Which option correctly defines the times operator function in Kotlin?
Choose the correct syntax to define the * operator function for a class Vector.
Kotlin
class Vector(val x: Int, val y: Int) { // Define operator fun times here }
Attempts:
2 left
💡 Hint
Remember the order: operator fun functionName(parameter: Type): ReturnType
✗ Incorrect
Option A uses correct Kotlin syntax for operator function: 'operator fun times(other: Vector): Vector = ...'. Others have syntax errors.
🚀 Application
expert2:00remaining
How many operator functions must be defined to support all arithmetic operators (+, -, *, /) for a class NumberBox?
If you want to support +, -, *, and / operators on your custom class NumberBox, how many operator functions must you define?
Attempts:
2 left
💡 Hint
Each operator corresponds to one operator function.
✗ Incorrect
Each arithmetic operator (+, -, *, /) requires its own operator function to be defined in the class, so 4 functions total.