Created
March 20, 2017 23:29
-
-
Save tpolecat/7361caa48a798cd9a717270b831128e0 to your computer and use it in GitHub Desktop.
This file contains 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
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