scala cookbook chapter 9. functional programming

用于记录在学习 scala cookbook过程中对于新知识或者不容易记忆的内容。结构与书的章节结构相同。

simplify anonymous functions

For instance, beginning with the most explicit form, you can print each element in the list using this anonymous function with the foreach method:

1
x.foreach ((i: Int) => println(i ))

As before, the Int declaration isn’t required:

1
x.foreach ((i) => println( i))

Because there is only one argument, the parentheses around the i parameter aren’t needed:

1
x.foreach (i => println(i ))

Because i is used only once in the body of the function, the expression can be further simplified with the _ wildcard:

1
x.foreach (println( _))

Finally, if a function literal consists of one statement that takes a single argument, you need not explicitly name and specify the argument, so the statement can finally be
reduced to this:

1
x.foreach (println)

declare function literal

You can declare a function literal in at least two different ways. I generally prefer the following approach, which implicitly infers that the following function’s return type is Boolean:

1
val f = (i: Int) => { i % 2 == 0 }

However, if you prefer to explicitly declare the return type of a function literal, or want to do so because your function is more complex, the following examples show different forms you can use to explicitly declare that your function returns a Boolean:

1
2
3
4
5
6
7
8
9
10
11
val f: (Int) => Boolean = i => { i % 2 == 0 }
val f: Int => Boolean = i => { i % 2 == 0 }
val f: Int => Boolean = i => i % 2 == 0
val f: Int => Boolean = _ % 2 == 0


val add = (x: Int, y : Int) => { x + y }
val add = (x: Int, y : Int) => x + y
// explicit approach
val add: (Int, Int) => Int = ( x,y ) => { x + y }
val add: (Int, Int) => Int = ( x,y ) => x + y