John Doe
John Doe

Reputation: 281

How to use type parameter for Scala implicit class?

I want to implement a retry mechanism for futures.

For example:

myFuture.map { data =>
   println(data)
   // ... do other stuff
}.recover {
   case e: MyException => logger.error("Something went wrong with XYZ", e)
   case _ => logger.error("Error!")
}.retry(Seq(1.seconds, 10.seconds, 30.seconds))

So the future should be retried after certain intervals.

My implementation looks as follows:

import akka.pattern.after
import akka.actor.Scheduler
import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration.FiniteDuration

object FutureExt {

  implicit class FutureUtils(f: Future[T]) {

    def retry[T](delays: Seq[FiniteDuration])(implicit ec: ExecutionContext, s: Scheduler): Future[T] = {
      f recoverWith { case _ if delays.nonEmpty => after(delays.head, s)(f.retry(delays.tail)) }
    }

  }

}

Unfortunately, the type parameter T cannot be resolved in the implicit class declaration. Any idea what's wrong with that?

Upvotes: 1

Views: 731

Answers (1)

danielnixon
danielnixon

Reputation: 4268

Nothing peculiar to implicit classes here. You've specified the type parameter T on the retry method but referred to it earlier than that (in the class parameters). Move the type param to the class itself (FutureUtils[T](f: ...)).

Upvotes: 3

Related Questions