来自上下文案例的隐式 val class

Implicit val from context case class

我有一个案例class:

case Context(tracker: Tracker)

我有一个带有 get def 的处理器 class,它期望 Tracker 的隐式参数定义为:

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

我有我的电话 class:

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

有没有一种简单的方法可以让我从 context -> Tracker 进行映射?我一直在尝试在 'repo' 的同伴中使用隐式定义,但在调用 process.get(id)

时仍然看到跟踪器的 'no implicit val available'

您可以在范围内定义隐式

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)

请参阅Where does Scala look for implicits?

中的隐式解析规则

如果您有权访问 ifContextThenTracker,您可以将其放入 Tracker 的伴生对象中。否则你可以导入隐式。