1

Where I can find Kotlin String plus method implementation?
When I track who calls String#plus, why Intellij IDEA point to "+" ? If String#plus is equal to "+", how does this implement?

wei ye
  • 73
  • 1
  • 7
  • 1
    For Kotlin/JVM, it is implemented within the compiler `javac.exe`. For constant expressions, its computed during compile-time already. I.e. `"hello" + "world"` is `"helloworld"` after compilation. Otherwise, before Java 9, it was `new StringBuilder().append(a).append(b)...toString()`. Since Java 9, there are more optimizations. Just take a look at your bytecode and you can see what it uses. – Zabuzard Dec 08 '22 at 10:29
  • See https://stackoverflow.com/questions/46512888/how-is-string-concatenation-implemented-in-java-9 for details. Again (at least for Kotlin/JVM), this is implemented in the compiler `javac.exe`, which creates specific bytecode. This also means that the implementation can vary between the Java compilers out there (Oracle, OpenJDK, Eclipse, ...). – Zabuzard Dec 08 '22 at 10:45
  • Srting::plus is an operator function, so `"str1".plus("srt2")` is equal to `"str1" + "str2"` if its what you asking for. – bylazy Dec 08 '22 at 13:39

1 Answers1

1

I finally find the answer.

  1. Where I can find Kotlin String plus method implementation?

Here I quote answer of ilya.gorbunov who is the member of JetBrains Team member.

"Currently, navigation to builtin sources may not work as expected in maven/gradle projects. You can find sources of builtins here kotlin/core/builtins at master·JetBrains/kotlin· GitHub 171. Note that the ‘native’ part of them do not have implementation bodies, as they are implemented as compiler intrinsics. If you’re more interested in what they are compiled to, you can inspect the generated bytecode with the “Show Kotlin bytecode” action."

Link is here Browsing source code of kotlin.kotlin_builtins like the .. operator

  1. When I track who calls String#plus, why Intellij IDEA point to "+" ? If String#plus is equal to "+", how does this implement?

The "+" operator is implemented by "Operator overloading" of Kotlin. When view String.kt source code, you can see the below code.

package kotlin
public class String : Comparable<String>, CharSequence {
    companion object {}
    /**
     * Returns a string obtained by concatenating this string with the string representation of the given [other] object.
     */
    @kotlin.internal.IntrinsicConstEvaluation
    public operator fun plus(other: Any?): String
    // omitting some source code 
}

Parameter of String#plus method is Any?, meaning we can use "+" operator concatenate any object after string object. Details of "Operator overloading" you can refer to Operator overloading Kotlin's Doc

wei ye
  • 73
  • 1
  • 7