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 −

Syntax

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

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

Syntax

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

Following is the syntax to call a curried function −

Syntax

strcat("foo")("bar")

You can define more than two parameters on a curried function based on your requirement. Try the following example program to show currying concept.

Example

object Demo {
   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
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

str1 + str2 = Hello, Scala!
scala_functions.htm

Useful Video Courses


Video

Scala Online Training

82 Lectures 7 hours

Arnab Chakraborty

Video

Apache Spark with Scala - Hands On with Big Data

23 Lectures 1.5 hours

Mukund Kumar Mishra

Video

Delta Lake with Apache Spark using Scala

52 Lectures 1.5 hours

Bigdata Engineer

Video

Apache Spark with Scala useful for Databricks Certification

76 Lectures 5.5 hours

Bigdata Engineer

Video

Machine Learning with Apache Spark 3.0 using Scala

69 Lectures 7.5 hours

Bigdata Engineer

Advertisements