scala支持函数式编程,将来编写Spark/Flink程序中,会大量使用到函数
语法
val 函数变量名 = (参数名:参数类型, 参数名:参数类型....) => 函数体
参考代码
scala> val add = (x:Int, y:Int) => x + y
add: (Int, Int) => Int = <function2>
scala> add(1,2)
res3: Int = 3
示例
方法无法赋值给变量
scala> def add(x:Int,y:Int)=x+y
add: (x: Int, y: Int)Int
scala> val a = add
<console>:14: error: missing arguments for method addbb;
follow this method with `_' if you want to treat it as a partially applied function
val a = add
方法转换为函数
,作为变量传递,就需要将方法转换为函数_
即可将方法转换为函数参考代码
scala> def add(x:Int,y:Int)=x+y
add: (x: Int, y: Int)Int
scala> val a = add _
a: (Int, Int) => Int = <function2>