Home > Net >  How to get the value for reified in Kotlin?
How to get the value for reified in Kotlin?

Time:01-24

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 :

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

CodePudding user response:

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.

  • Related