[Kotlin] What is Operator Functions?

GOAL

To understand operator functions in Kotlin.

What is operator function?

Operator function can upgrade certain functions to operators allowing their calls with the corresponding operator symbol such as + – / *. (Kotlin documentation)

Implementation example

operator fun Int.times(str: String) = str.repeat(this)
operator fun String.minus(str2: String) = this.replace(str2,"")

fun main() {
    println(3 * "hey")
    println("Mr.Jonny" - "Mr.")
}

output

heyheyhey
Jonny

Primary operators

a + ba.plus(b)
a – ba.minus(b)
a * ba.times(b)
a / ba.div(b)
a % ba.rem(b) a.mod(b)
a..ba.rangeTo(b)
a++a.inc()
a–a.dec()
+aa.unaryPlus()
-aa.unaryMinus()
!aa.not()

Check Kotlin language guide documentation for more information about operators and functions.