Skip to content

Instantly share code, notes, and snippets.

@soujiro32167
Created October 3, 2022 14:02
Show Gist options
  • Save soujiro32167/fa90f41d3b47c3847882809260cc7674 to your computer and use it in GitHub Desktop.
Save soujiro32167/fa90f41d3b47c3847882809260cc7674 to your computer and use it in GitHub Desktop.
Deriving typeclasses for zio-prelude newtypes outside of the object scope (scala2 only)
import $ivy.`dev.zio::zio-prelude:1.0.0-RC15`
import zio.prelude.Newtype
object newtypes {
def derive[A, STA <: Newtype[A], F[_]](implicit ev: STA <:< Newtype[A], typeClass: F[A]): F[STA#Type] =
typeClass.asInstanceOf[F[STA#Type]]
trait Auto {
implicit def auto[A, STA <: Newtype[A], F[_]](implicit ev: STA <:< Newtype[A], typeClass: F[A]): F[STA#Type] =
derive
}
object auto extends Auto
}
// Usage
object elsewhere {
object Foo extends Newtype[String]
type Foo = Foo.Type
trait Show[A] {
def show(a: A): String
}
implicit val stringShow: Show[String] = new Show[String]{ def show(a: String): String = a }
// import newtypes.auto._ // auto derive all the things
implicit val fooShow: Show[Foo] = newtypes.derive // semiauto derivation
implicitly[Show[Foo]]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment