首先,我必须澄清我不是在问什么是内联函数或什么是内联类。
在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
的定义是正确的吗?
inline
是允许的。我是说就像你自己所说的,如果尝试使用inline constructor
,它将无法编译,但对于这个内部内容却有效(并且该构造函数签名在规范中明确说明:https://kotlinlang.org/spec/built-in-types-and-their-semantics.html#built-in-array-types)。可能是一个特别编写的情况,或者也可能是内联构造函数在一般情况下是可能的,但被禁止了。 - cactustictacs