Scala (5): Currying Function

Currying Function is to allow others apply some parameters to your function. In some scenario, some people can apply some arguments to the function and others do rest later. In this case, we can use currying functions.

// normal function:
def multiply(m:Int, n: Int): Int = m * n
// currying function: if the function is applied curry, it seems to return an expression of an anonymous function
def multiply(m:Int) = (n: Int) => m * n
// simple currying function
def multiply(m: Int)(n: Int): Int = m * n

You can pass two parameters to this function.

multiply(2)(3) // output: 6

You also can pass partial parameters to this function and then apply to another variable/function. Partially uses an underscore.

Scala uses the underscore to mean different things in different contexts, but you can usually think of it as an unnamed magical wildcard. A partial function is only defined for certain values of the defined type.

val timesTwo = multiply(2) _ // Int => Int = <function1>
timesTwo(3) // output: 6

Of course, you can apply currying for any multi-parameters.

Here is an example using currying function.

def withClose(closeAble: {def close(): Unit })(op: {def close(): Unit } => Unit) {
  try {
    op(closeAble)
  } finally {
    closeAble.close()
  }
}

class Connection {
  def close() = println("close Connection")
}

val conn: Connection = new Connection()
withClose(conn)(conn => println("do something with Connection"))
// output: 
// do something with Connection
// close Connection
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s