Last active
May 24, 2022 16:59
-
-
Save nefilim/b7b2387883273b348502d0ed827f21e4 to your computer and use it in GitHub Desktop.
scala 2 implicit cats type class precendence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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