Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Created November 25, 2013 11:52
Show Gist options
  • Select an option

  • Save hanbzu/7640201 to your computer and use it in GitHub Desktop.

Select an option

Save hanbzu/7640201 to your computer and use it in GitHub Desktop.
Scala: Pattern to add missing methods to already existing classes.
// 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