4
add(x:Int)(y:Int) = x + y

add(5)(5) => 
add(5) _ => int => int = function

Of course we can use currying + a partially applied function for the creation of a new function, but I find it very difficult to read code like this.

Could you please show a useful example of currying with Scala?

Aaron M. Eshbach
  • 6,380
  • 12
  • 22

2 Answers2

1

OK here's one useful example - implicit parameters. Every method can have its last parameter list marked as implicit, which means that the compiler will automatically provide the needed arguments if it finds them in scope. If you have parameters other than the implicit ones, they have to be in a separate parameter list preceding the implicit one, which means that the method needs to be curried.

class MyClass(val value: String) {}

implicit def intToString(i: Int) = i.toString
implicit def doubleToString(d: Double) = d.toString
implicit def myClassToString(m: MyClass) = m.value

def append[T](t: T, s: String)(implicit ev: T => String) = t + s

val result1 = append(3, " is now a string")
val result2 = append(3.5, " is now a string")
val result3 = append(new MyClass("myClass"), " is now a string")
slouc
  • 9,508
  • 3
  • 16
  • 41
0

I also found it difficult to find a good example, so I wrote a blog post about it! A real world Currying example.

The answer basically comes down to this:

Currying is awesome. It allows us to easily reuse more abstract functions. We can easily create more specialized functions by partially applying curried functions. This is especially important because we often need to pass very specific functions to higher order functions like map, filter or reduce.

And here's an example from the blog post:

object CreditCard {
   def getPremium(totalCards: Int)(creditCard: CreditCard): Double = { ... } 
}

val creditCards: List[CreditCard] = getCreditCards()

val getPremiumWithTotal = CreditCard.getPremium(creditCards.length)_

val allPremiums = creditCards.map(getPremiumWithTotal).sum
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57