2

The ordering of implicit seems to matter when using shapeless. Look at the example code below where it will not work.

import shapeless._ case class Userz(i: Int, j: String, k: Option[Boolean]) object r { def func(): Userz = { val a = Userz(100, "UserA", Some(false)) val b = Userz(400, "UserB", None) val genA = Generic[Userz].to(a) val genB = Generic[Userz].to(b) val genC = genA zip genB val genD = genC.map(Mergerz) val User = Generic[Userz].from(genD) return User } } object Mergerz extends Poly1 { implicit def caseInt = at[(Int, Int)] {a => a._1 + a._2} implicit def caseString = at[(String, String)] {a => a._1 + a._2} implicit def caseBoolean = at[(Option[Boolean], Option[Boolean])] {a => Some(a._1.getOrElse(a._2.getOrElse(false)))} } r.func() 

And the code below which will work

import shapeless._ case class Userz(i: Int, j: String, k: Option[Boolean]) object Mergerz extends Poly1 { implicit def caseInt = at[(Int, Int)] {a => a._1 + a._2} implicit def caseString = at[(String, String)] {a => a._1 + a._2} implicit def caseBoolean = at[(Option[Boolean], Option[Boolean])] {a => Some(a._1.getOrElse(a._2.getOrElse(false)))} } object r { def func(): Userz = { val a = Userz(100, "UserA", Some(false)) val b = Userz(400, "UserB", None) val genA = Generic[Userz].to(a) val genB = Generic[Userz].to(b) val genC = genA zip genB val genD = genC.map(Mergerz) val User = Generic[Userz].from(genD) return User } } r.func() 

My question is, why does the order matters? I already tried importing the implicits which doesn't work.

1 Answer 1

1

Because type inference within a file basically works top-to-bottom. When it's typechecking func, it hasn't gotten to caseInt etc and doesn't know they are suitable. Annotating their types should work as well, and is generally recommended for implicits, but it may be problematic when using a library like Shapeless: see Shapeless not finding implicits in test, but can in REPL for an example.

Sign up to request clarification or add additional context in comments.

2 Comments

I always recommend annotating implicit definitions when working with shapeless. There are some fairly rare situations where this can be awkward, but for the most part it's both possible and desirable.
@MilesSabin Thanks for clarification!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.