Functions and Closures
1 Local Functions
Define functions insider other functions:
def processFile(filename: String, width: Int) = {
def processLine(filename: String, width: Int, line: String) = {
if (line.length > width)
println(filename + ": " + line.trim)
}
val source = Source.fromFile(filename)
for (line <- source.getLines())
processLine(filename, width, line)
}
2 First-Class Functions
Scala has first-class functions. Not only can you define functions and call them, but you can write down functions as unnamed literals and then pass them around as values.
A function literal is compiled into a class that when instantiated at runtime is a function value. Thus the distinction between function literals and values is that function literals exist in the source code, whereas function values exist as objects at runtime.
(x: Int) => x + 1
The => designates that this function converts the thing on the left (any integer x) to the thing on the right (x + 1). Function values are objects, so you can store them in variables if you like.
var increase = (x: Int) => x + 1
increase(10) // res0: Int = 11
increase = (x: Int) => {
Println("haha")
x + 1
}
Many Scala libraries give you opportunities to use them:
val someNumbers = List(-11, -10, -5, 0, 5, 10)
someNumbers.foreach((x: Int) => println(x))
someNumbers.filter((x: Int) => x > 0)
3 Short Forms of Function Literals
Scala provides a number of ways to leave out redundant information and write function literals more bfiefly.
someNumbers.foreach((x) => x > 0)
someNumbers.filter(x => x > 0)
4 Placeholder Syntax
To make a function literal even more concise, you can use underscores as placehohlders for one or more parameters.
someNumbers.filter(_ > 0)
_ > 0 is very short notation for a function that checks whether a value is greater than zero.
5 Partially applied functions
You can also replace an entire parameter list with an underscore:
def sum(a: Int, b: Int, c: Int) = a + b + c
val a = sum _
someNumbers.foreach(println _)