is there a way to make a constructor private and i...
# getting-started
b
is there a way to make a constructor private and instead provide a constructor function? I need to capture a reified type
Copy code
inline fun <reified T : Any> createEvent(
    endpointTarget: String,
    id: String,
    type: String,
    payload: T,
) = Event(
    endpointTarget = endpointTarget,
    id = id,
    type = type,
    payload = payload,
    typeInfo = typeInfo<T>()
)

class Event<out T : Any> private constructor(
    val endpointTarget: String,
    val id: String,
    val type: String,
    val payload: T,
    val typeInfo: TypeInfo,
)
1
y
You could make it
internal
, or use the companion object
b
image.png
p
@PublishedApi internal
1
Copy code
class Event<out T : Any> @PublishedApi internal constructor(
    val endpointTarget: String,
    val id: String,
    val type: String,
    val payload: T,
    val typeInfo: TypeInfo,
) {
    companion object {
        inline fun <reified T : Any> create(
            endpointTarget: String,
            id: String,
            type: String,
            payload: T,
        ) = Event(
            endpointTarget = endpointTarget,
            id = id,
            type = type,
            payload = payload,
            typeInfo = typeInfo<T>()
        )
    }
}
2
b
thank you
👍 1
a
I think what you are looking for is the
operator fun invoke
Like this:
Copy code
class Foo private constructor(val bar:Int){
    
    override fun toString():String{
        return "$bar"
    }
    
    companion object{
        operator fun invoke(barAsString : String): Foo{
            return Foo(barAsString.toInt())
        }
    }
}
p
In order to be inline to capture the reified type it would still need the constructor to be PublishedApi