0

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 ?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @llya for giving me a great hint to search further.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.