Kaj Koivunen
01/23/2023, 10:30 AMclass foo<T: Interface>() {
var something: T? = null
init {
something = T("bar") //doesn't work
}
}
I have an interface, the implementing classes of which have a constructor that takes one string. I'd like to make a class that can take any type that implements the interface and be able to cosntruct an instance of said class.Joffrey
01/23/2023, 10:31 AMT
that implements Interface
will have a constructor that takes a single string argument.Kaj Koivunen
01/23/2023, 10:34 AMVampire
01/23/2023, 10:37 AMKaj Koivunen
01/23/2023, 10:38 AMSam
01/23/2023, 10:40 AMclass Foo<T>(val something: T) {
constructor(init: (String) -> T): this(init("bar"))
}
class Bar(val value: String)
val foo = Foo(::Bar)
Joffrey
01/23/2023, 10:40 AMFoo
classKaj Koivunen
01/23/2023, 10:44 AMJoffrey
01/23/2023, 10:45 AMclass Foo<T>(private val createThing: (String) -> T) {
fun doStuff() {
val thing = createThing()
// ...
}
}