java - Kotlin 标准库中的 String 类是如何实现的?

标签 java kotlin

文件可以在这里找到 - 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/

相关文章:

java - 如何正确使用 Lombok @Data 和接口(interface)

java - 如何(完全)将 json 反序列化为通用列表?

具有可为空变量的 Kotlin 智能转换

java - 根据参数在数据库中查找固定数量的 RANDOM 用户的最佳方法是什么?

java - Android 振动已弃用。如何在 Android>= API 26 中使用 VibrationEffect?

java - 为什么我无法从模型中检索属性,但可以从 JSP 中检索属性?

java - 如果内容更改,自动调整舞台大小

java - Spring ehCache 根据一个bean值跳过缓存

kotlin - 切换到 Kotlin 1.3.30 仅在 Android API 21 上中断 hashCode

android - 为什么我得到 java.lang.NoSuchFieldError : No static field xxxx of type I in class Lpl/myapp/mobile/main/BR; or its superclasses?