简体   繁体   中英

Scala coding style

I have been unable to determine what the below code represents, as these syntax are not entirely listed in Scala documentation. Can someone shed some light on each of the below line? If the above title needs to be changed to something that can benefit others, please let me know.

val route =
  path("hello") {
    get {
      complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
    }
  }

Ref: http://doc.akka.io/docs/akka-http/current/scala/http/introduction.html#http-client-api

As you probably know, it's a route definition in akka http. They are very well described in akka documentation . This particular route works the following way:

  • path("hello"){...} - a directive that verifies the path
  • get{...} - a directive that verifies the http verb (method) So it translates to GET /hello
  • complete(HttpEntity(...)) is a response.

These are call-by-name parameters, which are described at various points in the Scala Language Specification. Basically, if you have a declaration like:

def path[R](string: String)(body: => R): R = ...

you will need to supply a string and a block of code ( body ), which is a call-by-name block. In this case, if body returns a result of type R , that will be the inferred return type of path . Thus, that method could be called as

path("hello") {
  "world"
}

The call-by-name block is not invoked until it is used.

Here is a nice explanation by Rob Norris: https://tpolecat.github.io/2014/06/26/call-by-name.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM