scala – 如何使用包含依赖类型的隐式参数组对此方法进行编码?
发布时间:2020-12-16 08:51:06 所属栏目:安全 来源:网络整理
导读:给定具有依赖类型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 im
给定具有依赖类型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的gist 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) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |