首先,我必须澄清,我不是在问什么是内联函数,或者什么是内联类. 在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)
    }

If you try to create that class in Kotlin and write an inline constructor for it you see that it's impossible and IDE refers to this error:

Modifier 'inline' is not applicable to 'constructor'

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

推荐答案

The ByteArray declaration you are looking at is not real, it’s a so called built-in type. This declaration exists for convenience, but is never truly compiled to a binary. (Indeed, on the JVM, arrays are special and don’t have corresponding class files anywhere.)

This constructor is marked inline because in practice the compiler emits the code corresponding to what would be its body at every call site. All the call-site checking is done accordingly (the lambda argument is treated in such a way that the compiler knows it’s going to be inclined).

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

Kotlin相关问答推荐

在Kotlin中处理结果的高阶函数

在Mapstruct中重用@映射定义

在Kotlin中,我是否可以访问已知的WHEN子句值?

为何Kotlin标准库中的AND和OR函数不能像&&和||一样进行短路运算?

在 Kotlin 中 import 如何找到文件路径?

如何处理基于枚举提前返回的 forEach 循环,Kotlin 中的一条路径除外

有没有办法重用 Job 实例?

Fragment的onDestroy()中是否需要将ViewBinding设置为null?

Kotlin 中多个 init 块的用例?

Kotlin 中的 Java Scanner 相当于什么?

Kotlinwhen表达式在使用主题时是否支持复合布尔表达式?

变量后的Android问号

作为 Kotlin 中的函数的结果,如何从 Firestore 数据库返回列表?

Kotlin默认使用哪种排序?

在kotlin中,如何模拟封装回调函数?

Kotlin 扩展函数 - 覆盖现有方法

内联 onFocusChange kotlin

Kotlin-将UTC转换为当地时间

在 Kotlin 中编写一个等于 Int.MIN_VALUE 的十六进制整数文字

如何在 Fragment 中使用 Anko DSL?