Currying syntax in scala

前端 未结 2 1811
执笔经年
执笔经年 2021-01-22 04:47

The syntax of currying in scala is for example

def f(x: Int, b: Int) = x + y

is

def f(x: Int)(b: Int) = x + y

And curr

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 05:00

    (Int, Int) => Int between : and = specify the function's return type, i.e, it says sum will return another method of signature (Int, Int) => Int which takes two Int and returns another Int, and this is the signature of your inner sumF function:

    You can rewrite this to the currying syntax as follows:

    def sum(f: Int => Int)(a: Int, b: Int): Int = {
        def sumF(a: Int, b: Int): Int =
            if (a > b) 0
            else f(a) + sumF(a + 1, b)
    
        sumF(a, b)
    }
    

    This will more or less do the same thing as the method defined in OP:

    sum(x => x)(3, 6)
    // res11: Int = 18
    

    But these two definitions are not exactly the same, for instance, for the currying syntax defined here, if you want to generate a new method from it, you have to specify the variable type, like:

    val mysum: (Int, Int)=> Int = sum(x => x)
    

    But for the one in OP, it can be simply val mysum = sum(x => x) as the return type of sum as already been specified.

提交回复
热议问题