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.

<strong>Scala</strong> supports first-class functions, which means you can express functions in function literal syntax, i.e., (x: Int)<br />

=> x + 1, and that functions can be represented by objects, which are called function values. The following<br />

expression creates a successor function for integers:<br />

var inc = (x:Int) => x+1<br />

Variable inc is now a function that can be used the usual way:<br />

var x = inc(7)-1<br />

It is also possible to define functions with multiple parameters as follows:<br />

var mul = (x: Int, y: Int) => x*y<br />

Variable mul is now a function that can be used the usual way:<br />

println(mul(3, 4))<br />

It is also possible to define functions with no parameter as follows:<br />

var userDir = () => { System.getProperty("user.dir") }<br />

Variable userDir is now a function that can be used the usual way:<br />

println( userDir )<br />

Partially Applied Functions<br />

When you invoke a function, you're said to be applying the function to the arguments. If you pass all the expected<br />

arguments, you have fully applied it. If you send only a few arguments, then you get back a partially applied<br />

function. This gives you the convenience of binding some arguments and leaving the rest to be filled in later.<br />

Following is a simple example to show the concept:<br />

import java.util.Date<br />

object Test {<br />

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

val date = new Date<br />

log(date, "message1" )<br />

log(date, "message2" )<br />

log(date, "message3" )<br />

}<br />

}<br />

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

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

}<br />

Here, the log( ) method takes two parameters: date and message. We want to invoke the method multiple times,<br />

with the same value for date but different values for message. We can eliminate the noise of passing the date to<br />

each call by partially applying that argument to the log( ) method. To do so, we first bind a value to the date<br />

parameter and leave the second parameter unbound by putting an underscore at its place. The result is a partially<br />

applied function that we've stored in a variable. We can now invoke this new method with only the unbound<br />

argument message as follows:<br />

import java.util.Date<br />

object Test {<br />

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

val logWithDateBound = log(new Date, _ : String)<br />

TUTORIALS POINT<br />

Simply Easy Learning

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

Saved successfully!

Ooh no, something went wrong!