Operator Overloading in Kotlin

July 25, 2020

What is operator overloading?

Operator overloading has its root in the language C++. It means, that you can define the behavior if an operator (e.g. +, -, *, …) is applied to your type. (Wikipedia )

In C++ this looks like the following.

Given we have a class Vector containing a x and a y field as coordinates. We can define the operator plus + as follows:

    Vector operator + (Vector const &obj) { 
         Vector res; 
         res.x = x + obj.x; 
         res.y = y + obj.y; 
         return res; 
    } 

In my opinion this technique has been forgotten since the days of C++ because it could easy mislead the developer and make code hard to read.

Usage In Kotlin

To show the usage of operator overloading in Kotlin we will implement a simple Vector class with some overloading for the +(plus) and *(times) operator.

data class Vector(var x: Int, var y: Int) {
    operator fun plus(vector: Vector) = Vector(x + vector.x, y + vector.y)

    operator fun times(factor: Int) = Vector(x * factor, y * factor)
}

We define the Vector class analogous to the C++ class above with two fields as the corresponding coordinates.

With operator fun <operator> we can define the behavior for the given operator.

To call these operators we simply use the + and * character.

fun main(args: Array<String>) {
    val v = Vector(1, 1)

    println(v + Vector(3, 0))
    println(v * 8)
}

Use operator overloading judicious

We should learn from the bad reputation that operator overloading got in C++.

I would suggest to only use operator overloading when there is a proper mathematical representation for your behavior. Otherwise it can quickly turn into misleading and non maintainable code.

Always think twice if the operator you are implementing has really no better name than a single symbol.

Wrapping up

Kotlin operators allow us to write code that comes pretty close to mathematical representations. This can make code shorter and clearer.
But they should be used with caution so they don’t end like the cout << "Hello World" example from C++.

The whole code it available on Github: kotlin_operator_overloading

Available operators

Valid operators are:

Left side describes the mathematical representation and the right word the corresponding operator verb.

Unary operations

  • +a unaryPlus
  • -a unaryMinus
  • !a not

Increments and Decrements

  • a++ inc
  • a– dec

Binary operations

  • a + b plus
  • a - b minus
  • a * b times
  • a / b div
  • a % b rem
  • a .. b rangeTo

in operator

  • a in b contains
  • a !in b !contains

Invoke operator

  • a() invoke

Augmented assignments

  • a += b plusAssign
  • a -= b minusAssign
  • a *= b timesAssign
  • a /= b divAssign
  • a %= b remAssign

Equality operators

  • a == b equals

All of these operators are described in depth in the official Kotlin documentation: Kotlin Documentation