How do I handle a nullable generics Class type in Kotlin?
Example function with generics:
fun <I> calculateStuff(valueType: Class<I>, defaultValue: I): I {
// do some work
return defaultValue;
}
Here is a calling function (note the 2nd param for calculateStuff(...))
fun doStuff() {
// works fine!
val myVar1 = calculateStuff(String::class.java, "")
// FAIL (null is not accepted... Error: "Cannot infer type parameter I in....")
val myVar2 = calculateStuff(String::class.java, null)
}
Work-around (change return type to I? AND defaultValue to I?):
fun <I> calculateStuff(valueType: Class<I>, defaultValue: I?): I? {
return defaultValue;
}
Preferred method, but does not seemed supported by Kotlin (note "String?::class.java"):
val myVar2 = calculateStuff(String?::class.java, null)
I really want to be able to send to the method (calculateStuff(...)) the return type, and if it can be null, as the first parameter... that way I ONLY have to null-check the return value if I pass a nullable Class in the first param.
Is this possible to do in Kotlin?