Home > Software engineering >  Implicit val from context case class
Implicit val from context case class

Time:09-21

I have a case class:

case Context(tracker: Tracker)

I have a processor class with a get def, that expects an implicit parameter of Tracker defined as:

class Processor(){
    def get(id: String)(implicit tracker: Tracker): Unit
}

and I have my calling class:

class repo(process: Processor){
    def get(id: String)(implicit ctx : Context): Unit{
        process.get(id)
    }
}

Is there an easy way for my to map from context -> Tracker? I've been trying to use an implicit def in the companion of 'repo' but am still seeing 'no implicit val available' for the Tracker when calling process.get(id)

CodePudding user response:

You can define implicit in the scope

implicit def ifContextThenTracker(implicit c: Context): Tracker = c.tracker

I've been trying to use an implicit def in the companion of 'repo' but am still seeing 'no implicit val available' for the Tracker when calling process.get(id)

Please see rules of implicit resolution in Where does Scala look for implicits?

You can put ifContextThenTracker into companion object of Tracker if you have access to it. Otherwise you can import implicit.

  • Related