Operator overloading in Kotlin

Level 5396 keystrokes

Functions marked operator with predefined names give a class its own operators: plus for +, minus for -, times for * and unaryMinus for unary -. Each one returns a new Vector instead of changing the original.

Kotlin code

// A data class, so toString() prints Vector(x=..., y=...)
1data class Vector(val x: Int, val y: Int) {
// operator plus defines v1 + v2: adds the components
2 operator fun plus(other: Vector) = Vector(x + other.x, y + other.y)
// operator minus defines v1 - v2
3 operator fun minus(other: Vector) = Vector(x - other.x, y - other.y)
// operator times defines v * 2 (Vector on the left, Int on the right)
4 operator fun times(scale: Int) = Vector(x * scale, y * scale)
// operator unaryMinus defines -v, which negates both components
5 operator fun unaryMinus() = Vector(-x, -y)
6}
7
// Two vectors to combine
8val v1 = Vector(3, 4)
9val v2 = Vector(1, 2)
10
// Calls v1.plus(v2): prints Vector(x=4, y=6)
11println(v1 + v2)
// Prints Vector(x=2, y=2)
12println(v1 - v2)
// Prints Vector(x=6, y=8)
13println(v1 * 2)
// Prints Vector(x=-3, y=-4); v1 itself is unchanged
14println(-v1)

Output

Vector(x=4, y=6)
Vector(x=2, y=2)
Vector(x=6, y=8)
Vector(x=-3, y=-4)
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • (× 15
  • )× 15
  • ,× 7
  • -× 6
  • =× 6
  • :× 5
  • .× 4
  • *× 3
  • +× 3
  • {× 1

More Kotlin examples at level 5

← Kotlin typing practice