14.06.2015 Views

Scala Tutorial

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

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

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

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

C:/>scala Test<br />

Value of a : 7<br />

Value of b : 5<br />

C:/><br />

Function with Variable Arguments<br />

<strong>Scala</strong> allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass<br />

variable length argument lists to the function. Following is a simple example to show the concept.<br />

object Test {<br />

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

printStrings("Hello", "<strong>Scala</strong>", "Python");<br />

}<br />

def printStrings( args:String* ) = {<br />

var i : Int = 0;<br />

for( arg scalac Test.scala<br />

C:/>scala Test<br />

Arg value[0] = Hello<br />

Arg value[1] = <strong>Scala</strong><br />

Arg value[2] = Python<br />

C:/><br />

Here, the type of args inside the printStrings function, which is declared as type "String*" is actually Array[String].<br />

Recursive Functions<br />

Recursion plays a big role in pure functional programming and <strong>Scala</strong> supports recursion functions very well.<br />

Recursion means a function can call itself repeatedly. Following is a good example of recursion where we calculate<br />

factorials of the passed number:<br />

object Test {<br />

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

for (i

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

Saved successfully!

Ooh no, something went wrong!