Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the value for reified in Kotlin?

I am getting started with kotlin and stuck with an issue.

I have a request function as below :

 fun dumRequest(): MyRequest {
        val token = JwtTokenGenerator.createToken(user)
        return MyRequest(token.serialize())
    }

And this is being passed as an argument to a function as :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val response: ResponseEntity<MyRequest> = callMyRequest(dumRequest())

And callMyRequest() is of generic type as :

private inline fun <reified T, reified Y> callMyRequest(request: Y): ResponseEntity<T> {
        val headers = HttpHeaders()
        headers.add(CONTENT_TYPE, "application/json")
        headers.add(AUTHORIZATION, request.token) // I want something like this here

        // other business logic
    }

I want to get the token from the request object which is being pass to callMyRequest() and set it in the AUTH header. But since this is a generic type, not sure how I can get the token field out of this ?

Any help would be highly appreciated.

TIA

>Solution :

I don’t really think you need to make Y reified here. It would suffice to restrict it to an interface containing the token, and then letting MyRequest implement that interface. Like <Y : AuthenticatedRequest>.

Actually, you don’t really need the Y type parameter at all, because you could just take the interface-type as a parameter directly.

Something like this:

interface AuthenticatedRequest {
    val token: String
}

data class MyRequest(override val token: String) : AuthenticatedRequest

private inline fun <reified T> callMyRequest(request: AuthenticatedRequest): ResponseEntity<T> {
    val headers = HttpHeaders()
    headers.add(CONTENT_TYPE, "application/json")
    headers.add(AUTHORIZATION, request.token) // I want something like this here

    // other business logic
}

It’s when you want to deserialize your result to T that the value of reified comes in handy. It might make you able to do something like response.readEntity<T>(), without having to deal with the class-objects directly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading