Jibidus
09/09/2025, 5:19 PMfun <T> buildInstance(clazz: Class<T>): T
… but this works only with classes which declare a constructor with a specific signature signature?
In such cases, constructor declaration in interfaces (or something similar) would help to keep code robust at runtime, right?
interface Buildable {
constructor(param: Sting)
}
fun <T: Buildable> buildInstance(clazz: Class<T>): T {
return clazz.constructor("param")
}
What do you think about this idea 💡?Hunter
09/09/2025, 6:51 PMinterface Buildable<T> {
companion fun build(param: String): T
}
fun <T : Buildable<T>> buildInstance(clazz: Class<T>): T {
return clazz.build("param")
}
hfhbd
09/09/2025, 7:00 PMkomu
09/09/2025, 7:37 PM(MyArguments) -> T
instead of KClass<T>
. Then I can pass a reference to the constructor. Of course it doesn't always work, but generally it does and is not as restrictive as requiring a constructor with a given signature.
When I really need that the "type" itself implements an interface, I use companion objects. Then I can just pass Foo
instead of Foo::class
.Jibidus
09/09/2025, 8:27 PMbuildInstance()
starts with a class, that's why a normal interface cannot solve this problem.
If we pass a function instead of a class @komu, the responsibility to choose how to create instance is moved to caller. So the problem is still present, in the caller, don't you think? Same with a companion as parameter.