diff options
author | Loic Descotte <loic.descotte@gmail.com> | 2017-11-11 08:04:42 +0100 |
---|---|---|
committer | Loic Descotte <loic.descotte@gmail.com> | 2017-11-11 08:24:30 +0100 |
commit | 2cd897dd1bb05981fac1fc9d61ee32f26a16c35b (patch) | |
tree | c2fb5fa0a884f501e053eb979e6dd0862f54336e /examples/shared/src/main/scala/eq.scala | |
parent | efe98a7d0b134415f3da0e7a7c3cb6ca5f2b44c4 (diff) | |
download | magnolia-2cd897dd1bb05981fac1fc9d61ee32f26a16c35b.tar.gz magnolia-2cd897dd1bb05981fac1fc9d61ee32f26a16c35b.tar.bz2 magnolia-2cd897dd1bb05981fac1fc9d61ee32f26a16c35b.zip |
scalajs cross build
Diffstat (limited to 'examples/shared/src/main/scala/eq.scala')
-rw-r--r-- | examples/shared/src/main/scala/eq.scala | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/examples/shared/src/main/scala/eq.scala b/examples/shared/src/main/scala/eq.scala new file mode 100644 index 0000000..8ee42a4 --- /dev/null +++ b/examples/shared/src/main/scala/eq.scala @@ -0,0 +1,41 @@ +package magnolia.examples + +import magnolia._ +import scala.language.experimental.macros + +/** typeclass for testing the equality of two values of the same type */ +trait Eq[T] { def equal(value: T, value2: T): Boolean } + +/** companion object to [[Eq]] */ +object Eq { + + /** type constructor for the equality typeclass */ + type Typeclass[T] = Eq[T] + + /** defines equality for this case class in terms of equality for all its parameters */ + def combine[T](ctx: CaseClass[Eq, T]): Eq[T] = new Eq[T] { + def equal(value1: T, value2: T) = ctx.parameters.forall { param => + param.typeclass.equal(param.dereference(value1), param.dereference(value2)) + } + } + + /** choose which equality subtype to defer to + * + * Note that in addition to dispatching based on the type of the first parameter to the `equal` + * method, we check that the second parameter is the same type. */ + def dispatch[T](ctx: SealedTrait[Eq, T]): Eq[T] = new Eq[T] { + def equal(value1: T, value2: T): Boolean = ctx.dispatch(value1) { + case sub => + sub.cast.isDefinedAt(value2) && sub.typeclass.equal(sub.cast(value1), sub.cast(value2)) + } + } + + /** equality typeclass instance for strings */ + implicit val string: Eq[String] = new Eq[String] { def equal(v1: String, v2: String) = v1 == v2 } + + /** equality typeclass instance for integers */ + implicit val int: Eq[Int] = new Eq[Int] { def equal(v1: Int, v2: Int) = v1 == v2 } + + /** binds the Magnolia macro to the `gen` method */ + implicit def gen[T]: Eq[T] = macro Magnolia.gen[T] +} |