kotlin - 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
定义如何正确?
解决方案
您正在查看的ByteArray
声明不是真实的,它是所谓的内置类型。这个声明是为了方便而存在的,但从来没有真正编译成二进制文件。(确实,在 JVM 上,数组是特殊的,在任何地方都没有对应的类文件。)
此构造函数被标记为内联,因为实际上编译器会在每个调用站点发出与其主体对应的代码。所有调用点检查都相应地完成(lambda 参数的处理方式使编译器知道它会倾斜)。
构造函数内联对于用户类是不可能的,因此inline
在用户代码中禁止使用该修饰符。
推荐阅读
- c - C歧义中的选择排序
- plugins - Flutter image_picker插件导致应用崩溃
- css - CSS - 边框图像的恒定大小
- c - 在 C 中解析一行以同时接收一个字符和一个两位数
- angular - 通过在 Angular 6 中创建自定义指令来启用/禁用按钮
- reactjs - 在 react js 中的 this.state 中写入嵌套对象
- numpy - 如何重复一个numPy数组值
- python - 根据索引号间隙填充缺失的行,为什么会起作用?- 熊猫系列
- r - 将数据帧拆分并水平合并为R中的单个字段
- spring-boot - 使用 Spring JPA 设置查询范围