【问题标题】:How is String class in Kotlin Standard library implemented?Kotlin 标准库中的 String 类是如何实现的?
【发布时间】:2020-03-18 18:12:23
【问题描述】:

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

我想了解显示的方法没有任何实现?还请简要介绍一下这段代码是如何工作的?

如果正在使用本机代码。请链接相同的源代码..

【问题讨论】:

  • 请将代码分享为格式化文本,而不是图片。
  • @Zabuza 我已链接到图片下方的文件。
  • String 在 JDK 上通过编译器魔术编译为 Java 字符串,因此您可以查看该源代码以了解它是如何工作的。 hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/…
  • @Tenfour04 好的,在图书馆里它实际发生在哪里? Kotlin String 到 Java String 类的链接。此外,如果您在同一个 kotlin 包中看到,还有 Array 类。它是如何映射到 Java 数组的?
  • @abitcode 我知道你链接了它,但是如果你直接分享它会增加你的观众和反应,也会增加投票。如果外部资源不可用,它会使问题自成一体。见How to Ask,谢谢。

标签: java kotlin


【解决方案1】:

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)

intern 等其他java.lang.String 方法在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 字符串。

【讨论】:

    猜你喜欢
    • 2019-12-17
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2013-10-02
    • 2021-06-29
    • 2018-04-28
    • 2016-10-27
    相关资源
    最近更新 更多