Kotlin 中的内联构造函数是什么?

YaM*_*MiN 9 oop constructor inline kotlin

首先,我必须澄清我不是在问什么是内联函数或什么是内联类。Kotlin 语言文档或规范中没有任何对内联构造函数的引用,但是如果您查看Arrays.kt源代码,您会看到这个类:ByteArray有一个内联构造函数:

/**
 * An array of bytes. When targeting the JVM, instances of this class are represented as `byte[]`.
 * @constructor Creates a new array of the specified [size], with all elements initialized to zero.
 */
public class ByteArray(size: Int) {
    /**
     * Creates a new array of the specified [size], where each element is calculated by calling the specified
     * [init] function.
     *
     * The function [init] is called for each array element sequentially starting from the first one.
     * It should return the value for an array element given its index.
     */
    public inline constructor(size: Int, init: (Int) -> Byte)
Run Code Online (Sandbox Code Playgroud)

让我们考虑我们要创建一个类似的类,如下所示:

    public class Student(name: String) {
        public inline constructor(name: String, age: Int) : this(name)
    }
Run Code Online (Sandbox Code Playgroud)

如果您尝试在 Kotlin 中创建该类并为其编写内联构造函数,您会发现这是不可能的,IDE 会引用此错误:

修饰符“内联”不适用于“构造函数”

那么让我们回顾一下,如何ByteArray定义是正确的?

And*_*lav 13

ByteArray您正在查看的声明不是真实的,它是所谓的内置类型。这个声明是为了方便而存在,但从未真正编译为二进制文件。(实际上,在 JVM 上,数组是特殊的,并且在任何地方都没有相应的类文件。)

这个构造函数被标记为内联,因为实际上编译器会在每个调用点发出与其主体相对应的代码。相应地完成所有调用站点检查(以编译器知道它会倾斜的方式处理 lambda 参数)。

构造函数内联对于用户类是不可能的,因此inline在用户代码中禁止使用修饰符。