文件可以在这里找到 - https://github.com/JetBrains/kotlin/blob/master/core/builtins/native/kotlin/String.kt
添加 String.kt 代码以供引用
package kotlin
/**
* The `String` class represents character strings. All string literals in
* Kotlin programs, such as `"abc"`, are
* implemented as instances of this class.
*/
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
/**
* Returns the character of this string at the specified [index].
*
* If the [index] is out of bounds of this string, throws an [IndexOutOfBoundsException] except in Kotlin/JS
* where the behavior is unspecified.
*/
public override fun get(index: Int): Char
public override fun subSequence(startIndex: Int, endIndex: Int): CharSequence
public override fun compareTo(other: String): Int
}
我想了解为什么显示的方法没有任何实现?另请简要说明此代码如何工作?
是否正在使用 native 代码。请链接相同的源代码..
最佳答案
Kotlin 的标准库在 Kotlin 支持的所有平台之间共享,因此它只包含方法的签名。几个类的实现与特定于平台的类相同:例如,在 Kotlin/JVM kotlin.text.StringBuilder
中被实现为 java.lang.StringBuilder
的类型别名。
但是,某些类型由编译器专门映射到平台类型(某些方法被删除,某些方法被重命名)。这些类型包括原始类型(Int、Byte 等)、String 和集合。
对于 JVM 来说,粗略的映射是:
kotlin.String.length => java.lang.String.length()
kotlin.String.compareTo(other: String) => java.lang.String.compareTo(java.langString anotherString)
kotlin.String.get(index: Int) => java.lang.String.charAt(int index)
kotlin.String.plus(other: Any?) is implemented as plain Java concatentation (it is implemented on compiler level with StringConcatFactory magic)
kotlin.String.subSequence(startIndex: Int, endIndex: Int) => java.lang.String.subSequence(int beginIndex, int endIndex)
其他java.lang.String
类似 intern
的方法kotlin.String
中不可用(但是,实际上可以直接引用java.lang.String
)。
在 Kotlin/Native 中 kotlin.String
使用 C++ 实现: https://github.com/JetBrains/kotlin-native/blob/045b20a36b8a1fe86716a99cb25f03021e583592/runtime/src/main/cpp/KString.cpp 。
JavaScript 实现也涉及内置 JavaScript 字符串。
关于java - Kotlin 标准库中的 String 类是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60728367/