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

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

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

>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.

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