What does the word “Action” do in a Scala function definition using the Play framework?

后端 未结 3 681
你的背包
你的背包 2021-02-02 00:45

I am developing Play application and I\'ve just started with Scala. I see that there is this word Action after the equals sign in the function below and before curl

3条回答
  •  不要未来只要你来
    2021-02-02 01:33

    The other answers deal with your specific case. You asked about the general case, however, so I'll attempt to answer from that perspective.

    First off, def is used to define a method, not a function (better to learn that difference now). But, you're right, index is the name of that method.

    Now, unlike other languages you might be familiar with (e.g., C, Java), Scala lets you define methods with an expression (as suggested by the use of the assignment operator syntax, =). That is, everything after the = is an expression that will be evaluated to a value each time the method is invoked.

    So, whereas in Java you have to say:

    public int three() { return 3; }
    

    In Scala, you can just say:

    def three = 3
    

    Of course, the expression is usually more complicated (as in your case). It could be a block of code, like you're more used to seeing, in which case the value is that of the last expression in the block:

    def three = {
       val a = 1
       val b = 2
       a + b
    }
    

    Or it might involve a method invocation on some other object:

    def three = Numbers.add(1, 2)
    

    The latter is, in fact, exactly what's going on in your specific example, although it requires a bit more explanation to understand why. There are two bits of magic involved:

    1. If an object has an apply method, then you can treat the object as if it were a function. You can say, for example, Add(1, 2) when you really mean Add.apply(1,2) (assuming there's an Add object with an apply method, of course). And just to be clear, it doesn't have to be an object defined with the object keyword. Any object with a suitable apply method will do.
    2. If a method has a single by-name parameter (e.g., def ifWaterBoiling(fn: => Tea)), then you can invoke the method like ifWaterBoiling { makeTea }. The code in that block is evaluated lazily (and may not be evaluated at all). This would be equivalent to writing ifWaterBoiling({ makeTea }). The { makeTea } part just defines an expression that gets passed in, unevaluated, for the fn parameter.

提交回复
热议问题