I want to create a function that is `inline fun <r...
# getting-started
c
I want to create a function that is
inline 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?
j
Like this maybe?
Copy code
inline fun <reified T> foo(): T {
    val type = T::class.createType()
    return if (type.isMarkedNullable) {
        impl(type) as T
    } else {
        impl(type)!!
    }
}
c
typeOf<T>()
is better than
T::class.createType()
here, I think
createType
doesn't know about the nullability since it's
KClass<T : Any>
that's what I'm doing right now but I'm a bit worried about that line in
isMarkedNullable
's documentation:
j
Maybe you could take a similar approach to the kotlin stdlib and just make a
fooOrNull
function to safely return nulls? Not really a solution, I know.
Seems to work fine in the playground. I think that statement only applies to non-reified types.
y
Just do
null is T
and based on that double-bang the return value or not
1
c
that's legal 🤔
nice, thanks!