What's an inline constructor in Kotlin?

First of all I have to clarify I’m not asking what’s an inline function is or what’s an inline class is.
There’s nowhere in Kotlin Language documentation or specification any reference to an inline constructor but if you look in Arrays.kt source you see this class: ByteArray has an inline constructor:

/**
 * 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)

Let’s consider we want to create a similar class, something like this:

    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’

So let’s recap, how ByteArray definition is correct?

1 Like

The inline constructor actually does not exist. I am not sure how it got to the standard library, maybe it is a remnant of a feature removed from the language at some moment, but right now, it is the only place it could be found and it could not be used anywhere else. You should use factory functions instead.

My personal opinion is that it should be also deprecated and removed in arrays.

1 Like

@darksnake Yeah, The inline constructor doesn’t exist and also in this sample secondary constructor doesn’t delegate to primary constructor which is odd.

ByteArray is a built-in type of Kotlin, and it has its members implemented as compiler intrinsics. Here this secondary constructor just doesn’t have a body in the source code, where such delegation usually happens.

These constructors are made inline in order to avoid instantiating init lambda object and to avoid boxing primitive results returned from that lambda.

We only allow inline constructors in built-in arrays as an exception, but we have an issue tracking inline constructors feature in general — KT-30915.

7 Likes

As an alternative you can still use an operator invoke on the companion object that works as a factory that looks similar.