Skip to content

Instantly share code, notes, and snippets.

@propensive
Last active June 8, 2016 09:58
Show Gist options
  • Save propensive/8894fd2a58ac93bfa2c3 to your computer and use it in GitHub Desktop.
Save propensive/8894fd2a58ac93bfa2c3 to your computer and use it in GitHub Desktop.
// 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
@propensive
Copy link
Author

@4lex1v If that works, great! I tend to ignore the type-specificity rules and go straight with stacked traits, but that's a useful optimization!

@yanns
Copy link

yanns commented Oct 15, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment