s

    Sebastien Leclerc Lavallee

    2 years ago
    Let say I have a class:
    @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?
    c

    Casey Brooks

    2 years ago
    The
    @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

    Robert Jaros

    2 years ago
    try this:
    import kotlinx.serialization.ImplicitReflectionSerializer
    import kotlinx.serialization.serializer
    
    @ImplicitReflectionSerializer
    fun isSerializable(obj: Any?): Boolean {
        return try {
            obj!!::class.serializer()
            true
        } catch (e: Exception) {
            false
        }
    }
    s

    Sebastien Leclerc Lavallee

    2 years ago
    @Robert Jaros Thanks for the answer! It did work 🙂