Last active
August 29, 2015 14:00
-
-
Save Chandler/11013054 to your computer and use it in GitHub Desktop.
function composition
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
abstract class PrintSomething() { | |
def apply(s: String): Unit | |
} | |
object PrintSomething { | |
/** | |
* @param printMethod a method that prints something | |
* @return a PrintSomething with an apply method | |
* equal to your printMethod | |
*/ | |
def build(printMethod: (String) => Unit): PrintSomething = | |
new PrintSomething() { | |
def apply(s: String) = printMethod(s) | |
} | |
/** | |
* Create a PrintSomething that is actually | |
* a composition of many PrintSomethings | |
* | |
* @param printers a sequence of printers | |
* @return a PrintSomething with an apply method | |
* that executes each printer you passed in | |
*/ | |
def compose(printers: Seq[PrintSomething]): PrintSomething = | |
build((s) => printers.foreach { p => p(s) }) | |
} | |
val printer1 = PrintSomething.build((s) => print("\nI love " + s)) | |
val printer2 = PrintSomething.build((s) => print("\nI hate " + s)) | |
val multiPrinter = PrintSomething.compose(Seq(printer1, printer2)) | |
printer1("cats") | |
// I love cats | |
printer2("cats") | |
// I hate cats | |
multiPrinter("cats") | |
// I love cats | |
// I hate cats |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment