aboutsummaryrefslogtreecommitdiff
path: root/examples/src/main/scala/eq.scala
diff options
context:
space:
mode:
authorJon Pretty <jon.pretty@propensive.com>2017-11-09 09:20:20 +0000
committerJon Pretty <jon.pretty@propensive.com>2017-11-09 09:20:20 +0000
commitc5c9c4f1432391f6af9202dd89872e5aae92ca58 (patch)
treec26bf5007c6204b9274993035c6e5cc9b9d4f9aa /examples/src/main/scala/eq.scala
parent3f23cb5bca4ea8be889b714008a85141fe5e213c (diff)
downloadmagnolia-c5c9c4f1432391f6af9202dd89872e5aae92ca58.tar.gz
magnolia-c5c9c4f1432391f6af9202dd89872e5aae92ca58.tar.bz2
magnolia-c5c9c4f1432391f6af9202dd89872e5aae92ca58.zip
Added Scaladocs
Diffstat (limited to 'examples/src/main/scala/eq.scala')
-rw-r--r--examples/src/main/scala/eq.scala25
1 files changed, 21 insertions, 4 deletions
diff --git a/examples/src/main/scala/eq.scala b/examples/src/main/scala/eq.scala
index 408f287..cd257f6 100644
--- a/examples/src/main/scala/eq.scala
+++ b/examples/src/main/scala/eq.scala
@@ -5,21 +5,38 @@ import scala.language.higherKinds
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)) }
+ 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.typeclass.equal(sub.cast(value1), sub.cast(value2)) }
+ 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]
}