Skip to content

Instantly share code, notes, and snippets.

@ShahOdin
Last active June 28, 2018 10:35
Show Gist options
  • Select an option

  • Save ShahOdin/e086ccdf20f820de7062940fe9c217b9 to your computer and use it in GitHub Desktop.

Select an option

Save ShahOdin/e086ccdf20f820de7062940fe9c217b9 to your computer and use it in GitHub Desktop.
implicit conversion of methods to Finagle Services
import com.twitter.util.Future
import com.twitter.finagle.Service
//the method that we want to pass around
def foo(x:Int): Future[String] = Future.value(x.toString)
//the construct that depends on Services
def bar(service: Service[Int,String]) = service
//Can create Services by fully implementing them as below:
val x: Service[Int,String] = new Service[Int, String] {
override def apply(request: Int) = foo(request)
}
bar(x)
//or we can do it without boiler-plate
val y: Service[Int,String] = foo _
bar(y)
//However can't pass the function directly
//bar(foo _)
//we can make use of in scope implicit to do this for us:
object Demo {
implicit class functionOps[A,B](foo: A => Future[B]){
def toService: Service [A,B] = new Service[A,B] {
override def apply(request: A) = foo(request)
}
}
//this works and is maybe more readable(explicit) but is ugly
bar((foo _).toService)
}
object DemoAlt {
implicit def functionOps[A,B](foo: A => Future[B]): Service[A,B] = new Service[A,B] {
override def apply(request: A) = foo(request)
}
//this works implicitly and is nicer but still annoying that you have to add _
bar(foo _)
}
@thomaslloyd

Copy link
Copy Markdown

In the first example... can't you just do bar(foo)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment