Scala functions and anonymous functions

A function is a first-class citizen

1. Pass a function as an argument to another function.
2. Use the function as the return value.
3. Assign the function to the variable.
4. Store functions in data structures.
In Scala, functions are just like ordinary variables, which also have the type of functions.
 
Two function types
1. Definition
In the Scala language, the format of a function type is A => B, which means a function that accepts a parameter of type A and returns a function of type B.
Example: Int => String is a function type that maps integers to strings
2. Code
  1. package test_first
  2. object DemoextendsApp{
  3. println( apply( layout,10))
  4. // 函数 f 和 值 v 作为参数,而函数 f 又调用了参数 v
  5. def apply(f:Int=>String, v:Int)= f(v)
  6. def layout(x:Int)="["+ x.toString()+"]"
  7. def operate(f:(Int,Int)=>Int)={f(4,4)}
  8. def add(x:Int,y:Int)=x+y
  9. println(operate(add))
  10. def greeting()=(name:String)=>{"hello"+" "+ name}
  11. val test = greeting()
  12. println(test("cakin24"))
  13. def multiplyBy(factor:Double)=(x:Double)=>factor*x
  14. val x=multiplyBy(10)
  15. println(x(50))
  16. }
3. Running results
[10]
8
hello cakin24
500.0
 
third-order function
1. Definition
Functions that take functions as parameters or return values ​​are called higher-order functions.
def operate(f:(Int,Int)=>Int)={f(4,4)}
def greeting() =(name:String) =>{"hello" + " " + name}
2. Code
  1. package test_first
  2. object DemoextendsApp{
  3. println( apply( layout,10))
  4. // 函数 f 和 值 v 作为参数,而函数 f 又调用了参数 v
  5. def apply(f:Int=>String, v:Int)= f(v)
  6. def layout(x:Int)="["+ x.toString()+"]"
  7. }
3. Running results
[10]
 
Four anonymous functions
A function constant, also known as a function literal.
In Scala, anonymous functions are defined in the format
(parameter list) =>{function body}
The left side of the arrow is the parameter list, and the right side is the function body.
After using anonymous functions, our code becomes more concise.
1. An anonymous function takes one parameter.
var inc = (x:Int) => x+1
The inc of the above example is now available as a function, which can be used as follows:
var x = inc (7) -1
2. Define multiple parameters in the anonymous function:
var mul = (x: Int, y: Int) => x*y
mul is now available as a function, which can be used as follows:
println (mul (3, 4))
3. Do not set parameters for anonymous functions, as follows:
var userDir = () => { System.getProperty("user.dir") }
userDir 现在可作为一个函数,使用方式如下:
println( userDir() )
 
五 匿名函数实例
  1. package test_first
  2. object DemoextendsApp{
  3. var factor =3
  4. val multiplier =(i:Int)=> i * factor
  5. println("multiplier(1) value = "+ multiplier(1))
  6. println("multiplier(2) value = "+ multiplier(2))
  7. }
 
六 匿名函数实例
multiplier(1) value = 3
multiplier(2) value = 6

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326988689&siteId=291194637