首页 > 解决方案 > 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)

假设我们要创建一个类似的类,如下所示:

    public class Student(name: String) {
        public inline constructor(name: String, age: Int) : this(name)
    }

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

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

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

标签: kotlinoopconstructorinline

解决方案


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

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

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


推荐阅读