首先,我必须澄清,我不是在问什么是内联函数,或者什么是内联类.
在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
的定义是如何正确的呢?