Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make the default constructor of a class generated from a Kotlin file private?

Tags:

kotlin

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.

like image 721
GabrielOshiro Avatar asked Sep 07 '17 02:09

GabrielOshiro


People also ask

Can a default constructor be private?

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.

Is it possible to create an object of the class which has a private default constructor?

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.

Why is Kotlin constructor private?

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 ...

How do you make a constructor object private?

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.


1 Answers

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.

like image 142
Federico Gaule Palombarani Avatar answered Oct 16 '22 09:10

Federico Gaule Palombarani