When programs get larger, you need some-to divide-them into smaller,
More manageable pieces. For dividing up control flow, Scala offers a approach familiar to all experienced programmers:divide the code into FUNCT Ions. In fact, Scala offers several ways to define functions that is not
Present in Java. Besides methods, which is functions that IS members
Of some object, there is also functions nested within functions, function literals, and function values. This chapter takes to a tour through all of
These flavors of functions in Scala
Generalizing's programming idea
A variety of ways to create functions
1. The most common-define a function is as a member of some object.
Such a function is called a method
Define a function by defining a method inside an object
2. Define the function in the body of the function, which is the local function
You can define functions inside and other functions. Just like local variables, such local functions is visible only in their enclosing block
The local function is visible only within the function closure in which it resides
3. Anonymous functions, or called function literals
val cubic = (x:int) + x * x * x
4. Ignore parameter types
Val nums = list (1,2,3,4,5)//> nums:list[int] = List (1, 2, 3, 4, 5) Nums.filter ((x) = x > 2) > Res0:list[int] = List (3, 4, 5)
5. Continue simplifying with placeholder
Val nums = list (1,2,3,4,5)//> nums:list[int] = List (1, 2, 3, 4, 5) Nums.filter (_ > 2) > Res0:list[int] = List (3, 4, 5)
Val F = (_: Int) + (_: int)//> f: (int, int) + int = <function2>
6. Partial function (patially applied functions)
Consider a scenario in which a function f has been defined, which accepts 5 parameters. When used, it is found that 2 parameters are always fixed. Then there is no simple way to define a function that is the same as the F function, but only accepts 3 parameters.
def sum5 (A:int, B:int, C:int, D:int, e:int) = a + B + C + D +e//> SUM5: (A:int, B:int, C:int, D:int, E:int) Int val sum3 = SUM5 (_: int, 2, _: int, 3,_: int)//> sum3: (int, I NT, int) = = Int = <function3>
7. Special way to define and invoke a function (special function call forms)
Indefinite parameter, default value, named parameter equals python similar
8. Tail recursion
def approximate (guess:double): Double = if (Isgoodenough (guess)) Guess else approximate (improve (guess))
Note that the recursive call was the last
Thing that happens in the evaluation of function approximate ' s body. Functions like approximate, which call themselves as their last action, is called
tail recursive. The Scala compiler detects tail recursion and replaces it with
A jump back to the beginning of the function, after updating the function
Parameters with the new values.
So the tail recursion in Scala can achieve almost the same efficiency as the loop statement.
Programming in Scala (Second Edition) reading notes 6 functions and closures