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

后端 未结 2 1100
有刺的猬
有刺的猬 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

    Currying is mostly used if the second parameter section is a function or a by name parameter. This has two advantages. First, the function argument can then look like a code block enclosed in braces. E.g.

    using(new File(name)) { f =>
      ...
    }
    

    This reads better than the uncurried alternative:

    using(new File(name), f => {
      ...
    })
    

    Second, and more importantly, type inference can usually figure out the function's parameter type, so it does not have to be given at the call site. For instance, if I define a max function over lists like this:

    def max[T](xs: List[T])(compare: (T, T) => Boolean)
    

    I can call it like this:

    max(List(1, -3, 43, 0)) ((x, y) => x < y)
    

    or even shorter:

    max(List(1, -3, 43, 0)) (_ < _)
    

    If I defined max as an uncurried function, this would not work, I'd have to call it like this:

    max(List(1, -3, 43, 0), (x: Int, y: Int) => x < y)
    

    If the last parameter is not a function or by-name parameter, I would not advise currying. Scala's _ notatation is amost as lightweight, more flexible, and IMO clearer.

提交回复
热议问题