If I create a Kotlin file MyTest.kt
package my.test
fun sayHello(): String = "Hello"
A class MyTestKt
will be generated and it can be accessed from java like this:
MyTestKt.sayHello() // Returns "Hello"
MyTestKt myTestKt = new MyTestKt() // Instantiate
I would like to make that constructor private. Is that possible? If so, how?
I know I can use an object
to create a singleton, that is not my question. I know I can create a class with a companion object
inside, that is also not my question.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
Yes we can have private constructors in a class and yes they can be made accessible by making some static methods which in turn create the new object for the class. So to make an object of this class, the other class has to use the static methods.
The kotlin private constructor is one of the constructor types, and it is used to stop the object creation for the unwanted case; if the user has decided to create the object for themselves accordingly, the memory will be allocated for the specific instance and also the class methods which is used for referring the ...
We can declare a constructor private by using the private access specifier. Note that if a constructor is declared private, we are not able to create an object of the class. Instead, we can use this private constructor in Singleton Design Pattern.
You can do something like this
@file:JvmName("Utils")
package demo
fun foo() {}
class Utils private constructor()
When you try to call Utils constructor from Java you get a "Utils has private access"
UPDATE
When using a private constructor() you are not able to access foo function.
I think this could be a design flaw, having a function not associated to any class-object. I have look into several kotlin standard library and I only found extension-functions as you want. In that case, for example, CollectionKt
, it cannot be instantiated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With