Last active
June 8, 2016 09:58
-
-
Save propensive/8894fd2a58ac93bfa2c3 to your computer and use it in GitHub Desktop.
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
// Define the following traits and companion object | |
// It's in Rapture Core (https://github.com/propensive/rapture-core) if you don't want to | |
trait LowPriorityDefaultsTo { implicit def fallback[T, S]: DefaultsTo[T, S] = null } | |
object DefaultsTo extends LowPriorityDefaultsTo { implicit def defaultDefaultsTo[T]: DefaultsTo[T, T] = null } | |
trait DefaultsTo[T, S] | |
// Then, assuming we want to specify a default for a type class like `Namer`, | |
case class Namer[T](name: String) | |
// where we have a couple of alternatives, | |
implicit val stringNamer = Namer[String]("string") | |
implicit val intNamer = Namer[Int]("int") | |
// we define the default one for a particular method like this: | |
def myMethod[T](implicit default: T DefaultsTo String, namer: Namer[T]) = namer.name | |
// Let's try it out in the REPL: | |
scala> myMethod | |
res0: String = string | |
scala> myMethod[Int] | |
res1: String = int |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For documentation purpose, the link to a similar implementation in the mongo scala driver: https://github.com/mongodb/mongo-scala-driver/blob/76dad47c8dbfc98b59867355a966cf95ef72e556/bson/src/main/scala/org/mongodb/scala/bson/DefaultHelper.scala