Category: Kotlin

[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.

[Kotlin] What is Infix Functions?

GOAL

To understand infix functions in Kotlin.

What is infix function?

In Kotlin, functions marked with the infix keyword can also be called using the infix notation (sited from the documentation of Kotlin). An example follows.

infix fun Int.add(a:Int): Int {
    return this+a
}

What is infix notation?

Infix notation is one of the notation types. In infix notation the operator is described in thee middle of the targets. + – * / are usually used as infix notation. (1+2, a-b)

  • Infix notation
    • (1+2)*(3-4)
  • Prefix notation (Polish notation)
    • *+12-34
  • Postfix notation (Reverse Polish notation)
    • 12+34-*

Implementation in Kotlin

fun pre_add(a:Int, b:Int): Int{
    return a+b
}

infix fun Int.in_add(a:Int): Int {
    return this+a
}

infix fun Int.in_sub(a:Int): Int = this-a

fun main() {
    println(pre_add(1,2))
    println(1 in_add 2)
    println(1.in_add(2))
    println(1 in_sub 2)
    println(1.in_sub(2))
}

output

3
3
3
-1
-1