Can I make a default constructor for a class created from a Kotlin private file?

If I create a Kotlin file MyTest.kt

package my.test
fun sayHello(): String = "Hello"

A class will be created MyTestKtand can be accessed from java as follows:

MyTestKt.sayHello() // Returns "Hello"
MyTestKt myTestKt = new MyTestKt() // Instantiate

I would like to make this constructor private. Is it possible? If so, how?


I know what I can use objectto create a singleton, this is not my question. I know that I can create a class with companion objectinside, this is not my question either.

+6
source share
1 answer

You can do something like this

@file:JvmName("Utils")

package demo

fun foo() {}
class Utils private constructor()

When you try to call the Utils constructor from Java, you get "Utilities have private access"

UPDATE () foo. , , , - -. kotlin, , . , , CollectionKt, .

0

All Articles