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 Number
separately.
Therefore, I suggest to not go with a generic function, but with multiple overloads:
fun List<Int>.firstOrZero() = if (isEmpty()) 0 else this[0]
fun List<Long>.firstOrZero() = if (isEmpty()) 0 else this[0]
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:
fun List<Int>.firstOrZero() = firstOrDefault { 0 }
fun List<Long>.firstOrZero() = firstOrDefault { 0 }
private inline fun <T:Number> List<T>.firstOrDefault(default: () -> T) : T {
if (isEmpty())
return default()
else
return this[0]
}
But for the specific case of firstOrZero()
I think it is an overkill.