Functions / methods in Scala. How does this work?

后端 未结 4 1671
旧巷少年郎
旧巷少年郎 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:42

    In your snippets there are several features of the Scala language and the compiler, let's analyse the ones I know:

    def route = ...
    

    defines a functions with no arguments and with result type determined by the return value of its body.

    path("hello") {
      ...
    }
    

    I'm not familiar with the path function itself but it seems as if there are three things going on in that snippet:

    • Currying: it's kinda "grouping arguments together";
    • Curly braces instead of round braces: to give a different look-and-feel to the call;
    • by-name parameters: to pass a code that will be evaluated only when needed.

    I don't want to spend time describing all of them as internet is full of resources that explain them greatly. But I want to link at least this great introductory article that helped me a lot in my early days.

    The linked article shows you a full example on how to use all three features to build your own control structure like the one of the code you're using.

    Moving on, the bit

    get {
      ...  
    }
    

    is again an application of the above points but this time there isn't currying so the curly braces are the only argument to the function.

    complete("Hello, World!")
    

    Is just a plain old function call.

    In short that code uses some "tricks" that transform a function call into sometehing that resembles a special language construct and this can create confusion for the beginners.

    This tecnique is used frequently to write Domani-Specific Languages (DSL) in Scala.


提交回复
热议问题