Betül Necanlı
Mar 12, 2023

--

Hello,

If I understand your question right,

Kotlin supports the use of generic types in suspend functions just like in regular functions. However, you're correct that at runtime, Kotlin's type erasure feature means that the type information is not available for generic types.

To work around this, you can use reified type parameters along with an inline function to capture the type information at compile time.

inline suspend fun <reified T> mySuspendFunction(value: T) {

// Use the type information of T here

}

the reified keyword allows us to access the type information of T at runtime, while the inline keyword tells the compiler to inline the function at the call site, so the type information is preserved.

You can then call this function like this:

mySuspendFunction("hello") // T is inferred to be String

mySuspendFunction(42) // T is inferred to be Int

--

--

Betül Necanlı
Betül Necanlı

Written by Betül Necanlı

Kotlin, Android Programming, Data Structures&Algorithms, Math. https://www.youtube.com/@betulnecanli

No responses yet