Sebastien Leclerc Lavallee
03/09/2020, 7:52 PM@Serializable
data class SomeClass(val a: Int)
And a function that can receive pretty much everythin:
fun someFunction(object: Any)
How can I check that the function’s parameter is Serializable? I did try something like:
when (object) {
is Serializable -> doSomething()
}
But that doesn’t work. Someone has some lights to help me?Casey Brooks
03/09/2020, 8:06 PM@Serializable
annotation doesn’t add any marker interfaces to the class. A better bet is probably to pass the serializer to that function directly (which is how the Kotlin libs handle this): fun <T> someFunction(obj: T, serializer: KSerializer<T>)
Robert Jaros
03/09/2020, 8:09 PMimport kotlinx.serialization.ImplicitReflectionSerializer
import kotlinx.serialization.serializer
@ImplicitReflectionSerializer
fun isSerializable(obj: Any?): Boolean {
return try {
obj!!::class.serializer()
true
} catch (e: Exception) {
false
}
}
Sebastien Leclerc Lavallee
03/10/2020, 12:42 AM