Skip to content

Instantly share code, notes, and snippets.

@vkostyukov
Created April 9, 2014 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkostyukov/10285203 to your computer and use it in GitHub Desktop.
Save vkostyukov/10285203 to your computer and use it in GitHub Desktop.
An example of usage implicit parameters of anonymous functions in Scala: Finagle + RactiveMongo
/**
* All the magic is done by Scala compiler.
*/
trait ImplicitMongoConnection[A] {
def withConnection(block: MongoConnection => A)
(implicit connection: MongoConnection): A = block(s)
}
/**
* This might be a separate file with service implementation.
*/
object FooService extends Service[Request, Response]
with ImplicitMongoConnection[Future[Response]] {
// we have to explicitly import implicit value into the scope
// we can do it at 'file' scope level if there's a bunch of services implemented in single file
import Main._
def apply(req: Request): Future[Response] = withConnection { implicit connection =>
// do all the magic here with 'connection'
// and pack the result into a future
Future.never
}
}
/**
* This might be a separate file with server/service configuration.
*/
object Main extends App {
val driver = new MongoDriver
// this value will be used in _all_ services
implicit val connection = driver.connection(List("localhost"))
// run the Finagle server on 'foo' service
val foo = FooService
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment