3
scala> import akka.http.scaladsl.server._; import Directives._
import akka.http.scaladsl.server._
import Directives._

假设我有两个函数,从某种类型 ( Int,比如说) 到 a 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>

这真是太好了,但隐含ConjunctionMagnet.fromRouteGenerator的 inakka.http.scaladsl.server让我有理由认为它可能直接在 akka-http 中是可能的

4

1 回答 1

1

相当于您给出的 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(_))
于 2017-07-20T12:17:26.437 回答