如果一个函数的参数是函数,这个函数就叫高阶函数。
高阶函数是java和scala的最大不同点。
scala> function//
scala> def fun1(name:String){print(name)} --最常见的显式定义行数
fun1: (name: String)Unit
scala> val fun1_v = fun1 _ --fun1 _是函数的原型
fun1_v: String => Unit = <function1> --箭头=>左边是输入String类型的参数,箭头=>右边是返回Unit类型的结果
注释:变量=functions,变量就可以当函数使用
scala> fun1_v("Spark")
Spark
scala> fun1_v("Scala")
Scala
scala> val fun2_v = (name:String) => println(name) --等号右边是匿名函数
fun2_v: String => Unit = <function1>
scala> fun2_v("Hadoop")
Hadoop
注释:箭头=>左边是输入,右边是输出
-------------------------------------------------------
scala> def person(id:Int,name:String){println(id+":"+name)} --def aa(){bb}
person: (id: Int, name: String)Unit
scala> person(1,"a1")
1:a1
scala> def person(id:Int,name:String) = println(id+":"+name) --def aa()=bb
person: (id: Int, name: String)Unit
scala> person(1,"a1")
1:a1
--函数等于匿名函数
scala> def person(id:Int,name:String) = ()=>println(id+":"+name)--def aa()=()=>bb
person: (id: Int, name: String)() => Unit
(id:Int,name:String)是等号左边的输入
()是等号右边的输入
Unit是最终返回类型
scala> person(1,"a1")
res186: () => Unit = <function0>
scala> def person(id:Int,name:String) = (age:Int)=>println(id+":"+name+":"+age)
person: (id: Int, name: String)Int => Unit
scala> person(1,"a1")
res188: Int => Unit = <function1>
scala> res188(18)
1:a1:18
scala> person(1,"a1")(18)
1:a1:18
scala> def person(id:Int,name:String) = (age:Int)=>{println(id+":"+name+":"+age);println("Hello...")}
person: (id: Int, name: String)Int => Unit
scala> person(1,"a1")(18)
1:a1:18
Hello...
!!scala 高阶函数,匿名函数
最新推荐文章于 2023-04-21 16:48:48 发布