Search code examples
kotlininfix-notation

How does plus sign refers to plus function in Kotlin and is it an infix function?


I have three questions.

1. how does plus sign (+) or in operator refer to plus() and contains() functions?

2. Are these infix functions?
They didn't have infix notation.

3. Is there any way that we can define custom characters as operators?


Solution

  • 1) & 2)

    + and in (and some others) are language built-in and are implicitly infix and have relevant operator functions (plus & contains).

    https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/plus.html#kotlin$plus(kotlin.String,%20kotlin.Any)/other

    https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/contains.html

    3) Yes, but you have to escape characters like this `$` or `^`

    infix fun Int.`√`(arg: Double): Double {
        return Math.pow(arg, 1.0 / this.toDouble())
    }
    
    infix fun Double.`^^`(arg: Double): Double {
        return Math.pow(arg, this)
    }
    
    fun main() {
        println( 3   `√` 27.0 )   // 3.0
        println( 3.0 `^^` 3.0 )   // 27.0
    }