Skip to content

Instantly share code, notes, and snippets.

@benhutchison
Last active August 16, 2016 12:11
Show Gist options
  • Save benhutchison/0411c04f3b27ecb586c5 to your computer and use it in GitHub Desktop.
Save benhutchison/0411c04f3b27ecb586c5 to your computer and use it in GitHub Desktop.
Shapeless Poly woes when combining default case with case over sealed hierarchy (and a solution)
Welcome to the Ammonite Repl 0.5.2
(Scala 2.11.7 Java 1.8.0_51)
@ load.ivy("com.chuusai" %% "shapeless" % "2.2.5")
@ import shapeless._
import shapeless._
@ sealed trait Country
defined trait Country
@ case object Germany extends Country
defined object Germany
@ case object Australia extends Country
defined object Australia
@ def eg1 = "Einstein" :: 1879 :: Germany :: HNil
defined function eg1
@ object ExamplePoly extends Poly1 {
implicit def default[T] = at[T](x => x)
implicit def yearsSinceBirth = at[Int](2016 - _)
//following http://stackoverflow.com/questions/20894593/subtype-polymorphism-in-shapeless-mapping
implicit def isAustralian[C <: Country] = at[C](_ == Australia)
}
defined object ExamplePoly
@ eg1.map(ExamplePoly)
Compilation Failed
Main.scala:272: could not find implicit value for parameter mapper: shapeless.ops.hlist.Mapper[cmd7.ExamplePoly.type,shapeless.::[String,shapeless.::[Int,shapeless.::[cmd3.Germany.type,shapeless.HNil]]]]
eg1.map(ExamplePoly)
^
//How I eventually solved it
@ trait IdentityDefault extends Poly1 {
implicit def default[T] = at[T](x => x)
}
defined trait IdentityDefault
@ object ExamplePoly3 extends IdentityDefault {
implicit def yearsSinceBirth = at[Int](2016 - _)
implicit def isAustralian[C <: Country] = at[C](_ == Australia)
}
defined object ExamplePoly3
@ eg1.map(ExamplePoly3)
res11: String :: Int :: Boolean :: HNil = ::("Einstein", ::(137, ::(false, HNil)))
@nightscape
Copy link

Looks like an ambiguous implicit, right?
implicit def default[T] matches everything and for cases where either yearsSinceBirth or isAustralian match as well the compiler doesn't know which to choose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment