Home > database >  Making private constructor and creating secondary constructor gives error in kotlin
Making private constructor and creating secondary constructor gives error in kotlin

Time:11-25

Below code snippet gives error. Can someone guide why this is happening?

class Test() private constructor {
        
    constructor(name: String): this() {
        println("test called constructor $name")
    }
   
}

fun main() {
    Test("hk")
}

Removing private constructor , this is working.

I tried to resolve this on my side. but I got no success.

CodePudding user response:

The () after Test is the constructor - it's shorthand for Test constructor() - think of it like a special function called constructor.

So if you want to make that function private, you need to explicitly use the constructor() name with the parentheses, and then you can add private before it.

class Test private constructor()

More info here: https://kotlinlang.org/docs/classes.html#constructors

CodePudding user response:

class Test{

  private  constructor(){}

  constructor(name: String): this() {
     println("test called constructor $name")
  }
}

CodePudding user response:

class Test private constructor() {

  constructor(name: String): this() {
    println("test called constructor $name")
  }

}

fun main() {
  Test("hk")
}
  • Related