Consider this Kotlin class that overloads the plus operator. What will be printed when the code runs?
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(2, 3) val p2 = Point(4, 5) val p3 = p1 + p2 println(p3) }
Remember that plus adds the x and y values separately.
The plus operator adds the x and y values of two Point objects. So (2+4, 3+5) = (6, 8).
Look at this Kotlin class that overloads the unary minus operator. What is the output?
data class Vector(val x: Int, val y: Int) { operator fun unaryMinus() = Vector(-x, -y) } fun main() { val v = Vector(7, -3) println(-v) }
The unary minus operator negates each coordinate.
The unary minus operator returns a new Vector with both x and y negated. So (7, -3) becomes (-7, 3).
This Kotlin class overloads the times operator. What will be printed?
class Matrix(val value: Int) { operator fun times(other: Matrix) = Matrix(this.value * other.value) override fun toString() = "Matrix(value=$value)" } fun main() { val m1 = Matrix(3) val m2 = Matrix(4) val m3 = m1 * m2 println(m3) }
The times operator multiplies the values inside the matrices.
The times operator returns a new Matrix with the product of the two values: 3 * 4 = 12.
Examine this Kotlin class that tries to overload the increment operator ++. What error occurs when compiling?
class Counter(var count: Int) { operator fun inc() { count += 1 } } fun main() { val c = Counter(5) c++ println(c.count) }
The inc operator must return the updated object.
The inc operator function must return the incremented object. Here it returns Unit (nothing), causing a compilation error.
In Kotlin, to overload the in operator (used like item in collection), which function signature is correct?
The function name must be contains and take one parameter.
The in operator calls the contains function with the item as parameter, returning a Boolean.