If I have: ```interface Cacheable { ...
# getting-started
d
If I have:
Copy code
interface Cacheable {

                                                               v This is an error... R needs to inherit from Any... but I'd like R to OPTIONALLY be nullable
    suspend operator fun <R> invoke(name: String, type: KClass<R>, vararg params: Any, block: suspend () -> R): R =
        cache(name, type, *params, block = block)
}
Where it's being used,
R
could be nullable or not nullable so I can't just use
R?
and
<R: Any>
... what other options do I have?
j
Use
KClass<R & Any>
?
d
That seems to not make the IDE complain, except for this:
Copy code
suspend inline fun <reified R> Cacheable.cache(
    name: String,
    vararg params: Any,
    noinline block: suspend () -> R
): R =
    cache(name, R::class, *params, block = block)
cache is defined the same as invoke...
j
Yeah because
R::class
cannot work if
R
is nullable
d
Any way to pass it down to
suspend fun <R> cache(name: String, type: KClass<R & Any>, vararg params: Any, block: suspend () -> R): R
?
On the call site:
Copy code
fun foo(): Something? = cache("name") { ... }
If Something is returned, I need KotlinX serialization to be able to transform it to json... if not, then I don't need the KClass at all...
j
Did you try passing down the serializer instead of the
KClass
? Maybe the reified
serializersModule.serializer<T>()
is more lenient with nullable types: https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/serializer.html
d
Thanks! I'll give that a try.
It works nicely, thanks again!
j
Good to hear!