简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM