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

Mihai Voicescu

10/22/2021, 4:14 PM
If I want to create a public inline method that is required to use a class hidden method ( internal/protected/private), the only way is to use internal+PublishedApi?
Copy code
abstract class Demo<RequestT> {
    @PublishedApi
    internal inline fun <reified T : RequestT> requestToJSON(payload: T): String {
        return Json.encodeToString(payload)
    }

    suspend inline fun <reified Res : RequestT> request(payload: Res): String {
        return req(requestToJSON(payload))
    }

    abstract suspend fun req(payload: String): String
}
j

Joffrey

10/22/2021, 7:34 PM
You should consider your inline reified method as simple sugar over a public API. If you want to hide a low level method, it means you probably need to expose a non-reified version of your public method (e.g. with an extra parameter like the class of T or something else), and then add the reified version that gets the extra information from the reified type. If you are using
reified
because you want to call a
reified
method yourself (like in the present case, where you are trying to call
encodeToString
), then it simply means you'll need to give up on the sugar for the call of that method and use the non-reified version (there is probably one in general). In this specific case, the non-reified version of
Json.encodeToString()
needs a
Serializer
, so you could just define your non-reified public method by asking for the same thing, and then make your reified version by calling this one and using the same trick as
encodeToString()
to get the extra information you need:
Copy code
private fun <T : RequestT> requestToJSON(payload: T, serializer: Serializer<T>): String {
        return Json.encodeToString(serializer, payload)
    }

    suspend fun <Res : RequestT> request(payload: Res, serializer: Serializer<T>): String {
        return req(requestToJSON(payload))
    }

    suspend inline fun <reified Res : RequestT> request(payload: Res): String {
        return request(payload, Json.serializersModule.serializer<Res>())
    }
4 Views