Kelvin Chung
07/22/2025, 6:45 AMinterface MyInterface<T> {
fun doSomething(): Array<T>
}
Is it possible to actually implement this interface generically?
class MyImpl<E> : MyInterface<E> {
override fun doSomething(): Array<E> {
// How do I create the array here?
}
}
Ronny Bräunlich
07/22/2025, 7:27 AMreified
type parameter.
interface MyInterface {
}
inline fun <reified T> MyInterface.doSomething(): Array<T> {
return emptyArray<T>()
}
class MyImpl : MyInterface {
}
fun main() {
val myImpl = MyImpl()
myImpl.doSomething<String>()
}
But in that case the implementation wouldn't be generic.Vampire
07/22/2025, 8:36 AMephemient
07/22/2025, 1:13 PMclass MyImpl<E : Any>(val clazz: Class<E>)
java.lang.reflect.Array.newInstance(clazz, size)
ephemient
07/22/2025, 1:18 PMArray<Any>
- I think your function would "work", although I can envision scenarios in which the caller may end up performing a check itself and fail at runtimeKelvin Chung
07/22/2025, 2:12 PMjava.lang.reflect.Array
wouldn't be available? (I tried seeing if there was something in KClass
that would allow me to create an array by reflection, but couldn't find anything)Youssef Shoaib [MOD]
07/22/2025, 3:54 PMinline fun <reified E> myInterfaceImpl(): MyInterface<E> = object: MyInterface<E> {
override fun doSomething(): Array<E> = emptyArray<E>()
}