Created
April 9, 2014 15:49
-
-
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
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
/** | |
* 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