Created
March 22, 2012 21:06
-
-
Save drdozer/2164568 to your computer and use it in GitHub Desktop.
Implicits example
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
def sort[A](items: List[A])(implicit ordA: Ordering[A]): List[A] = ... |
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
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()) | |
^ |
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
/** | |
* 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