CLOVIS
10/22/2025, 6:46 PMinline fun <reified T> foo(): T .
This function calls a function fun <T> impl(type: KType): T? .
I want the behavior that:
• If foo is called with a nullable type (e.g. foo<Int?>()), then nulls can be returned.
• If foo is called with a non-nullable type (e.g. foo<Int>()), if impl() returns null then it throws an NPE.
Is this possible?
Usually I would use overloads when I have two functions that only differ from the nullability of their parameters/receivers, but I don't think this is possible when they only differ by return type?Joshua Hansen
10/22/2025, 7:02 PMinline fun <reified T> foo(): T {
val type = T::class.createType()
return if (type.isMarkedNullable) {
impl(type) as T
} else {
impl(type)!!
}
}CLOVIS
10/22/2025, 7:09 PMtypeOf<T>() is better than T::class.createType() here, I think createType doesn't know about the nullability since it's KClass<T : Any>CLOVIS
10/22/2025, 7:09 PMisMarkedNullable 's documentation:Joshua Hansen
10/22/2025, 7:18 PMfooOrNull function to safely return nulls? Not really a solution, I know.Joshua Hansen
10/22/2025, 7:22 PMYoussef Shoaib [MOD]
10/22/2025, 7:53 PMnull is T and based on that double-bang the return value or notCLOVIS
10/22/2025, 8:24 PMCLOVIS
10/22/2025, 8:24 PM