Pagini
Workshops
Parteneri
Another powerful Scala feature today.
Implicits do a lot of black magic behind the scenes.
Today we learn how to control the magic.
You can find today's contents here.
We'll extend an existing well-known type with a few methods, use implicits to sort collections of our own datatypes and finally try to improve equality operations in Scala.
Int
to RichInteger
to enable this operation on integers.RichInteger
. It should check whether x is prime or not.gcd
method to RichInteger
. It should receive another y parameter of type Int
and compute the greatest common divisor of the two.Version
. It should have 3 fields, all integers: major
, minor
and patch
.<
operator on the new data type.Version
ordering. Its type should be Ordering[Version]
val order: Ordering[Version] = ???
sorted
method on it. Does it work?Eq
typeclass to offer support for equality testing.trait Eq[A] { def ===(l: A, r: A): Boolean def =!=(l: A, r: A): Boolean }
==
and !=
in the actual implementation.Ops
traits in order to provide an operator like notation to the implementing types. Use the following companion object for Eq in order to enable ===
and =!=
on any type class instance.object Eq { def apply[A](implicit instance: Eq[A]): Eq[A] = instance trait Ops[A] { def typeClassInstance: Eq[A] def self: A def ===(other: A) = typeClassInstance.===(self, other) def =!=(other: A) = typeClassInstance.=!=(self, other) } trait ToEqOps { implicit def toEqOps[A](target: A)(implicit instance: Eq[A]) = new Ops[A] { override val typeClassInstance = instance override val self = target } } object ops extends ToEqOps }
Int
s. Use the Eq
object to define it. Compare two integers using the ===
and =!=
methods. Does it work for other types as well (e.g. Strings)?==
vs. ===
and !=
vs =!=
?