How to code this method using an implicit parameter group that contains a dependent type?

For the Printer class with the dependent type 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 } } 

How to code this method:

 def r[A](x: A)(implicit printer: Printer, show: printer.Show[A]): String = printer.show(x)(show) 

I tried to adapt the working code in @MilesSabin gist https://gist.github.com/milessabin/cadd73b7756fe4097ca0 and @TravisBrown blog post https://meta.plasm.us/posts/2015/07/11/roll-your- own-scala / , but I can not find an encoding that works.

+7
scala dependent-type
source share
1 answer

You can force input of type output one step at a time by entering intermediate contexts:

 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) } 
0
source share

All Articles