Question: Suppose I have this external interface I...
# getting-started
k
Question: Suppose I have this external interface I have to implement:
Copy code
interface MyInterface<T> {
  fun doSomething(): Array<T>
}
Is it possible to actually implement this interface generically?
Copy code
class MyImpl<E> : MyInterface<E> {
  override fun doSomething(): Array<E> {
    // How do I create the array here?
  }
}
👀 1
r
That doesn't work unfortunately because the runtime wouldn't know what kind of array to create. Additionally, you cannot have a reified type parameter on a class. What would work would be an extension function with a
reified
type parameter.
Copy code
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.
v
And he cannot influence the interface, he said it is an external one
e
to create generic arrays you either need reified types or
Copy code
class MyImpl<E : Any>(val clazz: Class<E>)
java.lang.reflect.Array.newInstance(clazz, size)
alternatively you could try to perform an unsafe unchecked cast from an
Array<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 runtime
k
So, nothing within a KMP context, where
java.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)
y
You could do this:
Copy code
inline fun <reified E> myInterfaceImpl(): MyInterface<E> = object: MyInterface<E> {
  override fun doSomething(): Array<E> = emptyArray<E>()
}