Usefulness (as in practical applications) of Currying v.s. Partial Application in Scala

后端 未结 2 1102
有刺的猬
有刺的猬 2020-11-28 03:12

I\'m trying to understand the advantages of currying over partial applications in Scala. Please consider the following code:

  def sum(f: Int => Int) = (a         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 03:27

    I think it becomes clearer if you invert your curried example:

    def sum4(a: Int, b: Int)(f: Int => Int): Int = f(a) + f(b)
    
    val d = sum4(2, 2) { x =>
      x * x
    }
    

    It is more of an optical effect but you don’t need to use any parentheses around the whole expression. Of course you can achieve the same result using partial application or by creating a helper method to invert the arguments, sure. The point is, that you don’t have to do all of this if you start with a curried method in the first place. In that sense currying is more of an API and syntax sugar thing. It is not expected that you use

    val partial_sum4 = sum4(2, 2)
    

    anywhere in your code or that this is in any way especially meaningful to do. It is just that you get a nicely looking expression easily.

    (Well, and there are some advantages with respect to type inference…)

提交回复
热议问题