hobwekiva / newtypes

MIT License
115 stars 4 forks source link

Typeclasses for newtypes sometimes don't work. #3

Closed coltfred closed 6 years ago

coltfred commented 7 years ago

I created a newtype as follows:

object Bar {
  @newtypes.translucent type Foo = String
  implicit def eq: Eq[Foo] = Eq.fromUniversalEquals
  implicit val show: Show[Foo] = Show.fromToString
  implicitly[Eq[Foo]] //Works.
  implicitly[Show[Foo]] // Works
}

As you can see from my comments, the implicits for Eq and Show both work in the scope they were defined. However, if I try and import the implicits, it cannot find the one for Eq.

object OtherPlace {
  import Bar._
  // implicitly[Eq[Bar.Foo]] //Does not work.
  implicitly[Show[Bar.Foo]]
}

The error I get if I turn on log-implicits is this:

 internal/Foo.scala:44: eq is not a valid implicit value for cats.kernel.Eq[internal.Bar.Foo] because:
 reported error: type mismatch;
 found   : AnyRef => Boolean
 required: cats.kernel.Eq[internal.Bar.Foo]
    (which expands to)  cats.kernel.Eq[internal.Bar.Foo.Impl.T]

Any idea why this is happening or work arounds for it?

coltfred commented 7 years ago

This isn't a defect in newtypes, but seems to be a problem with the underlying pattern. A manual encoding of the Impl pattern seems to have the same issue. I'd love to hear if @alexknvl has any thoughts on it, regardless.

coltfred commented 6 years ago

@alexknvl Even though this isn't an issue directly with newtypes, if you have some ideas about ways to tackle the problem I'd love to hear them.

hobwekiva commented 6 years ago

@coltfred Replace eq with eqv above ;)

EDIT: that only partially solves the issue. Looking into Bar.Foo

hobwekiva commented 6 years ago

Nvm, seems to work fine. https://scalafiddle.io/sf/ZE4LvnK/0

coltfred commented 6 years ago

Well, either I'm crazy or something was fixed in a minor release of Scala (not sure what version I was testing on before). Sorry for the bother.