scala> import akka.http.scaladsl.server._; import Directives._
import akka.http.scaladsl.server._
import Directives._
假设我有两个从某种类型(比如Int
(到Route
的函数:
scala> lazy val r1: Int => Route = ???
r1: Int => akka.http.scaladsl.server.Route = <lazy>
scala> lazy val r2: Int => Route = ???
r2: Int => akka.http.scaladsl.server.Route = <lazy>
我可以这样编写一条路线:
scala> lazy val composite: Route = path("foo"){ r1(1) } ~ path("bar"){ r2(1) }
composite: akka.http.scaladsl.server.Route = <lazy>
我想做的是将函数组合与~
路径链接一起使用。也就是说,我希望它正常工作:
scala> lazy val composite: Int => Route = path("foo")(r1) ~ path("bar")(r2)
除了它没有:-(
<console>:31: error: type mismatch;
found : Int => akka.http.scaladsl.server.Route
(which expands to) Int => (akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult])
required: akka.http.scaladsl.server.Route
(which expands to) akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult]
lazy val composite: Int => Route = path("foo")(r1) ~ path("bar")(r2)
^
编辑
我正在尝试使用无点函数组合来做到这一点。正如Ramon在下面的答案所示,如果您愿意复制函数应用程序,则很容易做到这一点(但这是我想要避免的(。那是:
lazy val composite: Int => Route
= i => path("foo")(r1(i)) ~ path("bar")(r2(i))
注意
使用scalaz,我可以做到这一点:
scala> import akka.http.scaladsl.server._; import Directives._; import scalaz.syntax.monad._; import scalaz.std.function._
import akka.http.scaladsl.server._
import Directives._
import scalaz.syntax.monad._
import scalaz.std.function._
scala> lazy val r1: Int => Route = ???
r1: Int => akka.http.scaladsl.server.Route = <lazy>
scala> lazy val r2: Int => Route = ???
r2: Int => akka.http.scaladsl.server.Route = <lazy>
scala> lazy val composite = for (x <- r1; y <- r2) yield path("foo")(x) ~ path("bar")(y)
composite: Int => akka.http.scaladsl.server.Route = <lazy>
这很好,但是akka.http.scaladsl.server
中的隐含ConjunctionMagnet.fromRouteGenerator
让我有理由认为可以直接在akka-http中
相当于你给出的 scalaz 示例是:
lazy val composite: Int => Route =
(i) => path("foo")(r1(i)) ~ path("bar")(r2(i))
同样,您可以匿名化参数名称,但这会产生 2 个参数:
lazy val composite: (Int,Int) => Route = path("foo")(r1(_)) ~ path("bar")(r2(_))