Hi I am trying to write a generic function taking an optional list of types as argument like the following:
// Kotlin
fun <T: Throwable> callWithRetry(onError: List<T>?,
onAnother: List<T>?) {
onError?.forEach { println(it) }
onAnother?.forEach { println(it) }
}
However, whenever I am trying to call this function with both null parameters, it would complain Not enough information to infer type variable T
to me.
callWithRetry(onError = null, onAnother = null) // `Not enough information to infer type variable T`
The workaround I can find is to pass a empty list with actual type something like:
callWithRetry(onError = null, onAnother = emptyList<RuntimeException>())
But I feels like this is just ugly and probably wrong.
Doing the same thing in TypeScript would be fine:
// TypeScript
function callWithRetry<T, R>(onError?: Array<T>, onThrow?: Array<R>): boolean {
return false;
}
callWithRetry(null, null)
So my questions are:
- Am I doing the right thing in terms of defining nullable generic list?
- If this is not possible Kotlin, how could I approach this problem?
Thanks a lot!