I'm new to Kotlin, and I'm trying to write a simple generic method but it doesn't compile
inline fun <T:Number> List<T>.firstOrZero() : T {
if (isEmpty())
return 0 // this line doesn't compile
else
return this[0]
}
Is there a way to do it?
We can't really handle this case in a fully generic way in Kotlin. Whatever solution we choose, we have to handle each type of
Numberseparately.Therefore, I suggest to not go with a generic function, but with multiple overloads:
This should be potentially faster than generic solutions using reflection, because the type is resolved at the compile time instead of runtime.
If you have more cases like this, your cases are more complicated, etc. and you are concerned about the code duplication, you can inline the common code:
But for the specific case of
firstOrZero()I think it is an overkill.