SHARE
TWEET

Untitled

a guest Mar 20th, 2017 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. sealed trait MaybeNumeric[A]
  2. case class  YesNumeric[A](n: Numeric[A]) extends MaybeNumeric[A]
  3. case class  NoNumeric[A]() extends MaybeNumeric[A]
  4.  
  5. object MaybeNumeric {
  6.   implicit def instance[A](implicit ev: Numeric[A]): MaybeNumeric[A] =
  7.     YesNumeric(ev)
  8. }
  9.  
  10. def add[A](a: A, b: A)(implicit ev: MaybeNumeric[A] = NoNumeric[A]()): Option[A] =
  11.   ev match {
  12.     case NoNumeric() => None
  13.     case YesNumeric(ev) => Some(ev.plus(a, b))
  14.   }
  15.  
  16.  
  17.  
  18. scala> add(1.0, 2.0)
  19. res3: Option[Double] = Some(3.0)
  20.  
  21. scala> add(3,4)
  22. res4: Option[Int] = Some(7)
  23.  
  24. scala> add("five", "six")
  25. res5: Option[String] = None
RAW Paste Data
Top