:wave: Hi ! Have you ever been in a situation whe...
# language-proposals
j
👋 Hi ! Have you ever been in a situation where you have to write a function which create an instance from a class?
Copy code
fun <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?
Copy code
interface Buildable {
    constructor(param: Sting)
}

fun <T: Buildable> buildInstance(clazz: Class<T>): T {
    return clazz.constructor("param")
}
What do you think about this idea 💡?
h
A constructor on an interface doesn't make much sense in my opinion, since the desired behavior is more of a factory function, which imo is different from a constructor. I would like to see a contracted way of building instances though. Rust traits have something like this, since Rust uses factory functions over constructors. I'm not quite sure how it would work in kotlin, maybe something like contracted static functions?:
Copy code
interface Buildable<T> {
   companion fun build(param: String): T
}

fun <T : Buildable<T>> buildInstance(clazz: Class<T>): T {
   return clazz.build("param")
}
h
What’s the purpose of a buildable interface with such a constructor function? Why no normal interface called factory? And how should it work when an object implements the Buildable interface?
k
In cases like that, I tend to pass a function of type
(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
.
âž• 1
j
Thanks all for your feedbacks, You're right @Hunter, in my example we need a contract for a factory. A constructor is one way to have this factory, but certainly not the only. @hfhbd, a normal interface defines a contract on instances, not classes. And in my example,
buildInstance()
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.