09.10.2014 Views

Download Scala Tutorial (PDF Version) - Tutorials Point

Download Scala Tutorial (PDF Version) - Tutorials Point

Download Scala Tutorial (PDF Version) - Tutorials Point

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

logWithDateBound("message1" )<br />

logWithDateBound("message2" )<br />

logWithDateBound("message3" )<br />

}<br />

def log(date: Date, message: String) = {<br />

println(date + "----" + message)<br />

}<br />

When the above code is compiled and executed, it produces the following result:<br />

C:/>scalac Test.scala<br />

C:/>scala Test<br />

Thu Aug 18 01:41:07 GST 2011----message1<br />

Thu Aug 18 01:41:08 GST 2011----message2<br />

Thu Aug 18 01:41:08 GST 2011----message3<br />

C:/><br />

Currying Functions<br />

Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single<br />

parameter. Curried functions are defined with multiple parameter lists, as follows:<br />

def strcat(s1: String)(s2: String) = s1 + s2<br />

Alternatively, you can also use the following syntax to define a curried function:<br />

def strcat(s1: String) = (s2: String) => s1 + s2<br />

Following is the syntax to call a curried function:<br />

strcat("foo")("bar")<br />

You can define more than two parameters on a curried function based on your requirement. Let us take a complete<br />

example to show currying concept:<br />

object Test {<br />

def main(args: Array[String]) {<br />

val str1:String = "Hello, "<br />

val str2:String = "<strong>Scala</strong>!"<br />

println( "str1 + str2 = " + strcat(str1)(str2) )<br />

}<br />

}<br />

def strcat(s1: String)(s2: String) = {<br />

s1 + s2<br />

}<br />

When the above code is compiled and executed, it produces the following result:<br />

C:/>scalac Test.scala<br />

C:/>scala Test<br />

str1 + str2 = Hello, <strong>Scala</strong>!<br />

C:/><br />

TUTORIALS POINT<br />

Simply Easy Learning

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!