scala - How do I match types that don't have a specific typeclass instance? -


i define behavior types don't have instance typeclass:

  // given   trait sometypeclass[t]    // when have implicit sometypeclass[t]   def f[t: sometypeclass](x:t):unit = ???   // when don't have instance   def f[t !: sometypeclass](x: t):unit = ??? 

we handle difference within typeclass need create instances support generic behavior.

is there way negate type bound? way make function !: compile?

(i in vanilla scala, without scalaz, shapeless, etc)

is there way negate type bound?

no! syntax [t: sometypeclass] shorthand (implicit val t: sometypeclass[t]), , there no way "negate" that. overload method create ambiguity.

but can "nest" type classes.

trait existslowpri {   implicit def no[a]: exists[a] = exists.no } object exists extends existslowpri {   case class yes[a](peer: a) extends exists[a]   case object no extends exists[nothing]    implicit def yes[a](implicit peer: a): exists[a] = new yes(peer) } sealed trait exists[+a] 

example:

trait show[-a] {   def show(x: a): string }  def test[a](x: a)(implicit ex: exists[show[a]]): unit = println(   ex match {     case exists.yes(s) => s.show(x)     case exists.no     => "(no string repr)"   } )  implicit object showboolean extends show[boolean] {   def show(b: boolean) = if (b) "t" else "f"  }  test(123)   // (no string repr) test(true)  // t 

however, advise against doing this, because main point of implicits , type classes have explicit compiler failure if not in scope. way able compile have no guarantee correctly brought specific type class scope.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo