Linked Questions

Popular Questions

Functions / methods in Scala. How does this work?

Asked by At

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 following a course that introduces Akka HTTP. The code works, but I do not understand the route method:

import akka.http.scaladsl.server.Directives._

def route = path("hello") {
    get {
      complete("Hello, World!")

We are defining a method route that is being declared the value of path (imported from the line above), but then inside the path function we have something called get that I don't understand.

And when I am declaring path as a method, am I overriding it, or what's going on?

I would love if someone can explain what is going on, line by line. And don't mind that it is Akka involved. I want to know about the Scala syntax.


Thanks for all the great answers. I think I get it!

So to summarize my version of it.

path() is a function that wants a string. It returns another function that wants a Directive. And in Scala lingo we can do some kind of currying to directly send a directive to the returned function.

So everything in the block {} is sent to the function that path() returns. And since a block in Scala always returns the last line we are returning the get which by the same principles we call with complete.

get is also a function, that takes one parameter and that can be written as a block. This is equivalent to just writing get(complete("Hello, world")).

Thanks again!

Related Questions