什么是 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引用了这个错误:

修饰符"inline"不适用于"constructor">

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

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

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

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

最新更新