理解高阶函数的scala语法
我是scala新手,我需要了解下面的代码片段(更具体地说是sampleFunc val)的情况:理解高阶函数的scala语法,scala,Scala,我是scala新手,我需要了解下面的代码片段(更具体地说是sampleFunc val)的情况: val sampleFunc: Seq[Row] => (Int, Long, Boolean, Row, String) = (mem: Seq[Row]) => { //some code (a1,b1,c1,d1,e1) // returning the value
val sampleFunc: Seq[Row] => (Int, Long, Boolean, Row, String) = (mem: Seq[Row]) => {
//some code
(a1,b1,c1,d1,e1) // returning the value
}
spark.udf.register("sampleUDF", udf(sampleFunc,
StructType(
Seq(
StructField(a, IntegerType),
StructField(b, LongType),
StructField(c, BooleanType),
StructField(d, StructType(schema.fields)),
StructField(e, StringType)
)
)))
谢谢。好吧,我在代码片段中看到使用了
Spark
,但是让我们忽略这一点,只看一下sampleFunc
。所以一切都很简单:
接下来的宪法声明了功能本身:
val sampleFunc: Seq[Row] => (Int, Long, Boolean, Row, String) = ...
其中Seq[Row]
函数参数类型和(Int、Long、Boolean、Row、String)
函数结果。换句话说,您创建的变量类型为Function1[Seq[Row],(Int、Long、Boolean、Row、String)]
然后转到函数体或实现,如果您愿意的话
... = (mem: Seq[Row]) => {
//some code
(a1,b1,c1,d1,e1) // returning the value
}
其中mem
是已声明函数参数类型的变量,该变量应为相同类型或扩展函数声明类型中使用的类型。(函数参数是共变的。请参阅另一个好的SO帖子的更多示例:)
=>
语句说,在它转到函数体本身之后
如果您有更多的Java
背景或任何其他命令式语言背景,这也可以通过方法方式实现:
def sampleFunc(mem: Seq[Row]): (Int, Long, Boolean, Row, String) = {
//some code
(a1,b1,c1,d1,e1) // returning the value
}
希望这有帮助 //
//
val sampleFunc:Seq[Row]=>(Int,Long,Boolean,Row,String)=>{/*…*/;(a1,b1,c1,d1,e1)}
//同样的,写得不同:
//
val sampleFunc:Funtion1[Seq[Row],Tuple5[Int,Long,Boolean,Row,String]={mem=>/*…*/;(a1,b1,c1,d1,e1)}
- 值名称:这里没有什么特别的。只是代码中的另一个
val
- 值类型:它很长,但非常简单。正是
类型接受Function1
并返回Seq[Row]
。这正是scala更好的语法Tuple5[Int,Long,Boolean,Row,String]
- 实现:我们正在使用
语法创建采用=>
的函数。这里也没什么特别的Seq[Row]
val sampleFunc: Seq[Row] => Tuple5[Int, Long, Boolean, Row, String] =
(mem: Seq[Row]) => Tuple5(a1,b1,c1,d1,e1)
如果进一步将类型中的=>
替换为Function1
,则会得到:
Function1[Seq[Row], Tuple5[Int, Long, Boolean, Row, String]]
这意味着sampleFunc
是一个函数,它接受类型为Seq[Row]
的参数,并返回一个Tuple5[Int,Long,Boolean,Row,String]