Actual class cannot have only one private constructor


#1

I have a class in a multiplaform project, and I want the JS implementation has only one private constructor:

expect class JsonConverter {
    fun stringify(o: Any?): String
    fun <T> parse(text: String): T
}
actual class JsonConverter private constructor() {
    companion object {
        val instance = JsonConverter()
    }
    actual fun stringify(o: Any?): String {
        return JSON.stringify(o)
    }
    actual fun <T> parse(text: String): T {
        return JSON.parse<T>(text)
    }
}

However the compiler complains:
Actual class ‘JsonConverter’ has no corresponding expected declaration
unless I remove “private constructor ()” in the actual class.

Could anyone indicate how I can define an actual class with only one private constructor in a multiplatform project?


#2

Your expect class would also have to expect a private constructor. It currently tells the compiler a public constructor is expected. That is why you get a compiler error on your actual class.

If it is not possible to expect a private constructor, I am afraid it (currently) is not possible to do what you want.


#3

Have you tried this?

expect class JsonConverter expect private constructor() {
   ...
}

If that does not work, try to refactor the API. How are you actually intending to create instances of this class in your common module? Would it be feasible to replace this expected class with an interface?