Skip to content

Instantly share code, notes, and snippets.

@nefilim
Last active May 24, 2022 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nefilim/b7b2387883273b348502d0ed827f21e4 to your computer and use it in GitHub Desktop.
Save nefilim/b7b2387883273b348502d0ed827f21e4 to your computer and use it in GitHub Desktop.
scala 2 implicit cats type class precendence
object Precendence {
import cats.Monoid
import cats.kernel.Semigroup
import cats.instances.duration._ // <==== comment this out to see the difference
implicit val maxDurationSemigroup: Semigroup[Duration] = Semigroup((a, b) => if (a > b) a else b)
implicit def optionMonoid[A](implicit ev: Semigroup[A]): Monoid[Option[A]] =
new Monoid[Option[A]] {
def empty: Option[A] = None
def combine(x: Option[A], y: Option[A]): Option[A] =
x match {
case None => y
case Some(xx) => y match {
case None => x
case Some(yy) => Some(ev.combine(xx,yy))
}
}
}
def combine(rp1: Option[Duration], rp2: Option[Duration])(implicit mo: Monoid[Option[Duration]]): Option[Duration] = {
mo.combine(rp1, rp2)
}
def main(args: Array[String]): Unit = {
val rp1 = Some(2.minute)
val rp2 = Some(90.seconds)
println(combine(rp1, rp2))
println(combine(rp1, rp2)(optionMonoid[Duration](maxDurationSemigroup)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment