Scala Currying Functions

Advertisements


Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. Curried functions are defined with multiple parameter lists, as follows:

def strcat(s1: String)(s2: String) = s1 + s2

Alternatively, you can also use the following syntax to define a curried function:

def strcat(s1: String) = (s2: String) => s1 + s2

Following is the syntax to call a curried function:

strcat("foo")("bar")

You can define more than two parameters on a curried function based on your requirement. Let us take a complete example to show currying concept:

object Test {
   def main(args: Array[String]) {
      val str1:String = "Hello, "
      val str2:String = "Scala!"
      println( "str1 + str2 = " +  strcat(str1)(str2) )
   }

   def strcat(s1: String)(s2: String) = {
      s1 + s2
   }
}

When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
str1 + str2 = Hello, Scala!

C:/>


Advertisements
Advertisements