scalaimplicitgeneric-programmingshapelesspolymorphic-functions

Using Shapeless Poly in another method


I'm trying to use Shapeless Poly in another method like this:

object poly extends Poly1 {
  implicit val caseInt = at[Int](_.toString)
  implicit val caseString = at[String](_.toString)
}

def f[A, P <: Poly](a: A, p: P) = println(p(a))

this gives

could not find implicit value for parameter cse: shapeless.poly.Case[p.type,shapeless.::[A,shapeless.HNil]]

Any suggestion on how to make this works?


Solution

  • Poly.apply requires an implicit evidence of the Case implicit, which is what you provide it via the at[A] helper method.

    We need to add that same implicit requirement to f:

    import shapeless._
    import shapeless.PolyDefns.Case
    
    def f[A, P <: Poly](a: A, p: P)(implicit cs: Case.Aux[p.type, shapeless.::[A, HNil], String]) = 
      println(p(a))