快学Scala -06 --复杂函数

1.匿名函数

函数在内存当作是以对象的形式存在的,既然是对象就可以以变量指向对象来引用函数
1.1匿名函数的创建
//第一种方式
def add(n:Int,m:Int):Int = m+n
 var f = add _
-----------------------结果---------------------------
add: add[](val n: Int,val m: Int) => Int
f: (Int, Int) => Int = $Lambda$1287/1418797068@68d84800
res0: Int = 5

//第二种方式
var f = (n:Int,m:Int) =>m+n
f(2,3)
-----------------------结果---------------------------
f: (Int, Int) => Int = $Lambda$1294/22119690@261a4dc0
res0: Int = 5
//注意函数类型是 (Int,Int)
 
 
2.高阶函数
高阶函数就是参数是其他函数名的函数
定义的时候,函数的参数形式,以及返回类型必须写清楚
形如:f1:(Int,Int) => Int
//定义两个匿名函数
var f1 = (m :Int,n:Int) =>m+n
var f2 = (m :Int,n:Int) => m*n
//定义一个高阶函数
def call(m:Int,n:Int,f1:(Int,Int) => Int,f2:(Int,Int)=>Int):Int={
    if(m==0) f1(m,n) else f2(m,n)
}
call(3,5,f1,f2)
-----------------------结果---------------------------
res0: Int = 15
 
 

3.返回类型推断

def add(m:Int ,n:Int):Int = m+n
add(2,3)

def add(m:Int ,n:Int) = m+n
def contact(m:String,n:String)=m+n

//但是不建议省略但会类型
 
4.调用函数返回数
def ff(m:Int)={
    def f(x:Int)=m*x
    f _  //返回函数的引用
}
var f = ff(2)
f(3)

以上句等于这一句 : ff(2)(3)
f: Int => Int = $Lambda$1343/1000988898@5b4b2aae
res0: Int = 6
 
 
 
def ff(m:Int)={
    (x:Int) => m*x   //匿名函数,最后一句自动返回,不知道返回类型所以不写
}
ff(2)(3)
res0: Int = 6
 
 

猜你喜欢

转载自www.cnblogs.com/feixiaobai/p/738c78bf3e343f9c9406face55c0f2a6.html
今日推荐