Home > Net >  Why calling a private constructor in Kotlin results in error as "Cannot access <init>&quo
Why calling a private constructor in Kotlin results in error as "Cannot access <init>&quo

Time:06-22

If you use factory method in Kotlin to create an object, like:

class Person private constructor(val firstName:String , val lastName: String) {
    companion object {
        fun createPerson(firstName: String, lastName: String): Person {
            return Person(firstName, lastName)
        }
    }
}

Calling factory method works:

val person1 = Person.createPerson("Niels", "Abel")

And also, of course, you can't call the constructor directly:

val person2 = Person("Évariste", "Galois")

The resultant error is: Cannot access '<init>': it is private in 'Person'

But, why they choose to report this particular error? What is <init>?

CodePudding user response:

<init> is the name of the constructor, so the error message is basically saying that your constructor is inaccessible, exactly what you would expect.

<init> happens to be the special name that Java uses for the constructors of a class. When you are compiling Kotlin for the JVM, the Kotlin compiler also uses the same name for the constructors of Kotlin classes, in order to be compatible with Java. The JVM even reserves this name so that it cannot be used in regular methods. (I don't know about what happens with Kotlin on other platforms)

The Kotlin compiler doesn't have to show the name <init> literally in the error message though. They could have replaced with something more intuitive like "constructor", but that's one extra case they have to handle - they have to specifically check for the name being <init>, and replace it with something else. As far as I can see on YouTrack, no one has raised an issue about this asking for this to be changed yet.

See also: What is an <init> method in Java? Can it be overridden?

  • Related