3

在科特林源代碼的源代碼實現string.kt的,我不明白如何實現String.kt的長度,它是如下:我無法理解在科特林

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. 
*/ 
public operator fun plus(other: Any?): String 

public override val length: Int 

public override fun get(index: Int): Char 

public override fun subSequence(startIndex: Int, endIndex: Int): CharSequence 

public override fun compareTo(other: String): Int} 

var len:Int = "abc".length; // len = 3 where to run the length??

在哪裏實現長度函數?

+0

當你寫這個''abc「.length'並返回你想要的長度字符串? –

+0

是的,我可以得到正確的結果。我只想知道在哪裏實施kotlin源代碼。我已經添加了上面的String.kt。 –

回答

9

字符串函數是Kotlin認爲Intrinsic函數的示例。它們是基於它們正在運行的平臺而定義的,您將無法在源代碼中找到它們的實現。

對於JVM,它們將直接映射到相應的本機java.lang.String方法。這可以確保沒有運行時間開銷並利用在java標準庫中完成的優化。

+0

正如你所說,我可以找到內在函數嗎? –

+0

沒有'實現',當這些函數被調用時,編譯器會執行一些自定義代碼生成來產生結果。一些映射函數可以在https://github.com/JetBrains/kotlin/blob/master/compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/IntrinsicMethods.java找到。 – Kiskae