molnarpw February 2016

What does this mean in Scala?

Im checking out the http4s library, and seeing some unknown syntax.

val route = HttpService {
  case GET -> Root / "hello" =>
    Ok("Hello world.")
}

I looked into the source, and HttpService is an object, but how does the rest come in place?

Answers


Diego Martinoia February 2016

You are probably reading the code of some sort of web application that relies on an underlying framework such as Spray.

What that code does is specifying a route, i.e. a URL address of the webapp.

In the specific case, you are saying that should you get an http request on the port the server is listening on, of type GET, for url "rootUrl/hello", you should respond with a status code of 200 (OK) and the content of your response should be the "Hello world." string.


dth February 2016

Since Scala is so flexible in overloading syntax, you can often not tell definitively what is actually happening without any context.

In this case the "case" keyword is a first hint, it can only occur in match-expressions and partial functions, so this

{
  case GET -> Root / "hello" => Ok("Hello world.")
}

has to be a partial function.

This function is clearly passed as argument of some method or function given by HttpService. In case of a single argument one can let out the parentheses. So the code actually means this:

val route = HttpService({
  case GET -> Root / "hello" => Ok("Hello world.")
})

Now, if, as you say, HttpService is an object, its apply-method is called. So I would expect to find an apply method in this object (or some class or trait it inherits from) with a single argument taking a function or a partial function.


Angelo Genovese February 2016

A few pieces of information that might help when looking at code like this:

  • Calling an object or class as a function calls the appropriate apply method if there is one
  • Parentheses are often optional

so another way to rewrite the code above would be:

val route = HttpService.apply({
  case GET -> Root / "hello" =>
    Ok("Hello world.")
})

As noted in Diego's answer, the function passed to apply in this case goes from some sort of HTTP request to some sort of HTTP response.

Post Status

Asked in February 2016
Viewed 2,102 times
Voted 12
Answered 3 times

Search




Leave an answer