给定一个类型类 Printer
具有依赖类型 Show[A]
:
trait Printer {
type Show[A]
def show[A](x: A)(implicit z: Show[A]): String
}
object Printer {
// the intent here is this is the dumb fallback
// and a user can have a better alternative in scope
implicit val dumbPrinter: Printer = new Printer {
type Show[A] = DummyImplicit
def show[A](x: A)(implicit z: DummyImplicit): String = x.toString
}
}
我如何编码这个方法:
def r[A](x: A)(implicit printer: Printer, show: printer.Show[A]): String =
printer.show(x)(show)
我一直在尝试调整@MilesSabin 的要点 https://gist.github.com/milessabin/cadd73b7756fe4097ca0 中的工作代码和@TravisBrown 的博文 https://meta.plasm.us/posts/2015/07/11/roll-your-own-scala/ ,但我找不到有效的编码。
最佳答案
您可以通过引入中间上下文来一次强制类型推断:
object example {
trait AnyPrinter {
type Show <: AnyShow
}
trait AnyShow {
type X
def apply(x: X): String
}
def print[P <: AnyPrinter](implicit p: P): print[P] = new print[P]
class print[P <: AnyPrinter] {
def it[E](e: E)(implicit s: P#Show { type X = E }): String = s(e)
}
// the intent here is this is the dumb fallback
// and a user can have a better alternative in scope
implicit object DumbPrinter extends AnyPrinter {
type Show = AnyDumbShow
}
trait AnyDumbShow extends AnyShow {
def apply(x: X): String = x.toString
}
case class DumbShow[Z]() extends AnyDumbShow { type X = Z }
implicit def dumbShow[Z]:DumbShow[Z] = DumbShow()
val buh: String = print.it(2)
}
关于scala - 如何使用包含依赖类型的隐式参数组对该方法进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37479148/