Skip to content

Instantly share code, notes, and snippets.

@drdozer
Created March 22, 2012 21:06
Show Gist options
  • Save drdozer/2164568 to your computer and use it in GitHub Desktop.
Save drdozer/2164568 to your computer and use it in GitHub Desktop.
Implicits example
def sort[A](items: List[A])(implicit ordA: Ordering[A]): List[A] = ...
scala> loudThenQuiet(new TV())
Turning the TV volume up
Turning the TV volume down
scala> loudThenQuiet(new OperaSinger())
Asking the diva to belt it out
Begging the diva to save our ears
scala> loudThenQuiet(new Baby())
<console>:41: error: Could not work out how to adjust the volume for a Baby.
loudThenQuiet(new Baby())
^
/**
* Adjust the volume on something that produces noise.
*/
@annotation.implicitNotFound("Could not work out how to adjust the volume for a ${A}.")
trait VolumeAdjuster[A] {
def makeLouder(a: A): Unit
def makeQuieter(a: A): Unit
}
case class TV()
case class OperaSinger()
case class Baby()
def loudThenQuiet[A](a: A)(implicit va: VolumeAdjuster[A]): Unit = {
va.makeLouder(a)
java.lang.Thread.sleep(2000)
va.makeQuieter(a)
}
implicit object TvRemote extends VolumeAdjuster[TV] {
def makeLouder(tv: TV) { println("Turning the TV volume up using the TV Remote control") }
def makeQuieter(tv: TV) { println("Turning the TV volume down using the TV Remote control") }
}
implicit object Conductor extends VolumeAdjuster[OperaSinger] {
def makeLouder(os: OperaSinger) { println("Conductor is asking the diva to belt it out"); }
def makeQuieter(os: OperaSinger) { println("Conductor is begging the diva to save our ears"); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment