Search code examples
kotlinintrinsics

Where is function definition of kotlin plus operator?


I was just looking into the source code of Primitives.kt file in kotlin source to see the function code for 'plus' operator.

/** Adds the other value to this value. */
public operator fun plus(other: Int): Int

Can someone help me guide where is the code for this function ?


Solution

  • These functions in Primitives.kt are implemented as compiler intrinsics. It means that when the compiler encounters such function invocation, it replaces that with some predefined sequence of lower level code or a call to another function.

    For example in Kotlin/JVM, the function call Int.plus(Int): Int in this code

    fun test(x: Int, y: Int) {
        x.plus(y)
    }
    

    is replaced with the bytecode sequence something like this:

        ILOAD 0
        ILOAD 1
        IADD
    

    And an example when an intrinsic function call is replaced with another function call:

    fun test(x: Int, y: Int) {
        x.compareTo(y)
    }
    

    is compiled to:

        ILOAD 0
        ILOAD 1
        INVOKESTATIC kotlin/jvm/internal/Intrinsics.compare (II)I
    

    Here the static function Instrincs.compare(Int, Int) is called instead of the member function Int.compareTo(Int).