Created
November 25, 2013 11:52
-
-
Save hanbzu/7640201 to your computer and use it in GitHub Desktop.
Scala: Pattern to add missing methods to already existing classes.
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
| // Here we add the 'userInput' method to the Future class | |
| implicit class FutureCompanionOps(f: Future.type) extends AnyVal { | |
| def userInput(message: String): Future[String] = Future { | |
| readLine(message) | |
| } | |
| } | |
| // Without the sintactic sugar: | |
| class FutureCompanionOps(f: Future.type) extends AnyVal { | |
| def userInput(message: String): Future[String] = Future { | |
| readLine(message) | |
| } | |
| } | |
| implicit def f2ops(f: Future.type) = new FutureCompanionOps(f) | |
| // This implicit conversion will be called every time you call | |
| // a non-existing method on the Future companion object | |
| // – Future.userInput thus automatically becomes f2ops(Future).userInput. | |
| // The 'extends AnyVal' part is just an optimization telling the compiler | |
| // to avoid instantiating the FutureCompanionOps object where possible | |
| // and call its methods directly. | |
| // whenever you want to add missing methods to an already existing | |
| // class implementation, you should use this pattern. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment