Skip to content

Instantly share code, notes, and snippets.

@tpolecat
Created March 20, 2017 23:29
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 tpolecat/7361caa48a798cd9a717270b831128e0 to your computer and use it in GitHub Desktop.
Save tpolecat/7361caa48a798cd9a717270b831128e0 to your computer and use it in GitHub Desktop.
sealed trait MaybeNumeric[A]
case class YesNumeric[A](n: Numeric[A]) extends MaybeNumeric[A]
case class NoNumeric[A]() extends MaybeNumeric[A]
object MaybeNumeric {
implicit def instance[A](implicit ev: Numeric[A]): MaybeNumeric[A] =
YesNumeric(ev)
}
def add[A](a: A, b: A)(implicit ev: MaybeNumeric[A] = NoNumeric[A]()): Option[A] =
ev match {
case NoNumeric() => None
case YesNumeric(ev) => Some(ev.plus(a, b))
}
scala> add(1.0, 2.0)
res3: Option[Double] = Some(3.0)
scala> add(3,4)
res4: Option[Int] = Some(7)
scala> add("five", "six")
res5: Option[String] = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment