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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Partially Applied Functions<br />

Currying Functions<br />

Functions Call-by-Name<br />

Typically, parameters to functions are by-value parameters; that is, the value of the parameter is determined before<br />

it is passed to the function. But what if we need to write a function that accepts as a parameter an expression that<br />

we don't want evaluated until it's called within our function? For this circumstance, <strong>Scala</strong> offers call-byname<br />

parameters.<br />

A call-by-name mechanism passes a code block to the callee and each time the callee accesses the parameter, the<br />

code block is executed and the value is calculated.<br />

object Test {<br />

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

delayed(time());<br />

}<br />

}<br />

def time() = {<br />

println("Getting time in nano seconds")<br />

System.nanoTime<br />

}<br />

def delayed( t: => Long ) = {<br />

println("In delayed method")<br />

println("Param: " + t)<br />

t<br />

}<br />

Here, we declared the delayed method, which takes a call-by-name parameter by putting the => symbol between<br />

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

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

C:/>scala Test<br />

In delayed method<br />

Getting time in nano seconds<br />

Param: 81303808765843<br />

Getting time in nano seconds<br />

C:/><br />

Here, delayed prints a message demonstrating that the method has been entered. Next, delayed prints a message<br />

with its value. Finally, delayed returns t.<br />

Functions with Named Arguments<br />

In a normal function call, the arguments in the call are matched one by one in the order of the parameters of the<br />

called function. Named arguments allow you to pass arguments to a function in a different order. The syntax is<br />

simply that each argument is preceded by a parameter name and an equals sign. Following is a simple example to<br />

show the concept:<br />

object Test {<br />

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

printInt(b=5, a=7);<br />

}<br />

def printInt( a:Int, b:Int ) = {<br />

println("Value of a : " + a );<br />

println("Value of b : " + b );<br />

}<br />

}<br />

TUTORIALS POINT<br />

Simply Easy Learning

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

Saved successfully!

Ooh no, something went wrong!