trait Encoder[From, To] {
def encode(x: From): To
}
object Encoder {
implicit val thingToString: Encoder[Thing, String] = new Encoder[Thing, String] {
def encode(x: Thing): String = x.toString
}
}
trait Config {
type Repr
}
class MyConfig extends Config { type Repr = String }
//class ConcreteConfig { type Repr = String }
class Api[T](val config: Config) {
def doSomething(value: T)(implicit encoder: Encoder[T, config.Repr]): Unit = {}
}
case class Thing(a: Int)
object Test extends App {
import Encoder._
val api = new Api[Thing](new MyConfig)
api.doSomething(Thing(42))
}
到api.doSomething
调用失败编译:斯卡拉:类型类实例的隐式的查找路径依赖型
could not find implicit value for parameter encoder: Encoder[Thing,Test.api.config.Repr]
如果我改变class Api[T]
的构造方法的签名,这样只有一个ConcreteConfig
,那么编译器可以知道config.Repr == String
和隐式查找成功。但是这对我的用例并不适用。
是否有任何其他方式来指导隐式查找?我是否因为缺少类型优化或某种东西而丢失了类型信息?
'api.config.Repr' _is_一个稳定的路径,虽然你的第二句话是正确的。 –