Functions / methods in Scala. How does this work?

后端 未结 4 1672
旧巷少年郎
旧巷少年郎 2021-02-14 03:04

I am new to Scala and have a hard time understanding all the ways of declaring and using functions. Can someone please explain, step by step, what is going on here?

I am

4条回答
  •  被撕碎了的回忆
    2021-02-14 03:57

    There are many things that are going on here and this is a pretty complex example to understand scala. But i'll try.

    The route's type is Route, which is a type alias defined as type Route = RequestContext ⇒ Future[RouteResult] where RequestContext ⇒ Future[RouteResult] is a function that consumes RequestContext and produces Future[RouteResult].

    path is a method that creates a Directive[Unit]. There is an implicit conversion that converts Directive[Unit] into a function Route => Route (simplified). A function can be called by method apply or with compiler sugar as (???) or {???}.

    get is a method that creates a Directive[Unit] too and similar approach applies to it.

    complete is of type StandardRoute that extends Route.

    Knowing all this, we could uglify your example that will be written as

    path("hello").apply { ctx =>
        val inner: Route = { ctx =>
          ctx.complete("done")
        }
        get.apply(inner).apply(ctx)
    }
    

提交回复
热议问题