[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 + b | a.plus(b) |
a – b | a.minus(b) |
a * b | a.times(b) |
a / b | a.div(b) |
a % b | a.rem(b) a.mod(b) |
a..b | a.rangeTo(b) |
a++ | a.inc() |
a– | a.dec() |
+a | a.unaryPlus() |
-a | a.unaryMinus() |
!a | a.not() |
Check Kotlin language guide documentation for more information about operators and functions.