https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dave08

09/21/2023, 4:26 PM
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

Joffrey

09/21/2023, 4:29 PM
Use
KClass<R & Any>
?
d

dave08

09/21/2023, 4:31 PM
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

Joffrey

09/21/2023, 4:32 PM
Yeah because
R::class
cannot work if
R
is nullable
d

dave08

09/21/2023, 4:33 PM
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

Joffrey

09/21/2023, 4:37 PM
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

dave08

09/22/2023, 6:04 AM
Thanks! I'll give that a try.
It works nicely, thanks again!
j

Joffrey

09/26/2023, 11:54 AM
Good to hear!