Search code examples
scalagenericssttp

Scala function that takes dynamic class as parameter


Alrighty, a realtime example of what I'm trying to do. I am using Scala Sttp as my Http Client. I have bunch of requests, so I wanted to make it more abstract. I wanted to generalise all get requests under abstract function that would look something like:

  def getRequest(
    uri: String,
    queryString: String,
    responseClass: **ANYCLASS**, --> I am unsure how to do this
    trackingId: String,
    component: String = "http-v2-client-get-request",
    numberOfRetries: Int = 0
  ): Either[HttpErrorInfo, **ANYCLASS**] = {

    val request = basicRequest
      .get(uri"$uri")
      .response(asJson[responseClass])
  }
  ...

So my question is how to replace responseClass signature so I can provide any case class so it gets mapped correctly.

Sorry if my question is somewhat bad, I am new to Scala and still learning how to dynamically do things


Solution

  • Try

      def getRequest[T: Decoder](
        uri: String,
        queryString: String,
        trackingId: String,
        component: String = "http-v2-client-get-request",
        numberOfRetries: Int = 0
      ): Either[HttpErrorInfo, T] = {
    
        val request = basicRequest
          .get(uri"$uri")
          .response(asJson[T])
      }
      ...
    

    Please notice the context bound : Decoder.