Last active
June 28, 2018 10:35
-
-
Save ShahOdin/e086ccdf20f820de7062940fe9c217b9 to your computer and use it in GitHub Desktop.
implicit conversion of methods to Finagle Services
This file contains 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
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 _) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the first example... can't you just do
bar(foo)
?