匿名函数
Lamda (参数) => {函数体}
(t1, t2) => {
(t1._1, t1._2 + t2._2)
}
下划线的各种用法
Scala中的下划线使用总结
【Scala】Scala中的_ 和 _*分别代表什么
函数与方法
闭包
老师的资料上写:
一个函数在实现逻辑时,将外部变量i引入到函数内部,改变了这个变量的生命周期,称之为闭包
传名和传值函数
Scala中 => Unit 与 () =>Unit的区别
scala-传名函数和传值函数
IDEA
偏函数
偏函数:它是PartialFunction[A,B]的一个实例,A代表参数类型,B代表返回类型,常用来做输入模式匹配。
def func(str:String):Int={
if (str.equals("a")) 97
else 0
}
//偏函数
def func2:PartialFunction[String,Int]={
case "a"=>97
case _=>0 //default:
}
println(func2("a"))
println(func2("bbbd"))
97
0
Collect
上面这篇文章的关键句:
在调用map方法时,一旦遍历到值"seven",并调用f(x),因为类型不符合模式匹配中的Int类型,导致抛出MatchError错误。而collect方法在调用pf(x)之前,调用了pf的isDefinedAt(x)作了一次过滤。
如果在前面的map例子中再增加一个case子句,对String类型的值进行处理,则case语句就从偏函数变成了满足所有条件的“全”函数。
collect:通过执行一个并行计算(偏函数),得到一个新的数组对象
val chars = Array('a','b','c')
val newchars = chars.collect(fun)
println("newchars:"+newchars.mkString(","))
//我们通过下面的偏函数,把chars数组的小写a转换为大写的A
val fun:PartialFunction[Char,Char] = {
case 'a' => 'A'
case x => x
}
/**输出结果是 newchars:A,b,c */
toBuffer
toBuffer()方法用于返回包含集合中所有元素的缓冲区。
这里的偏函数实现的其实类似是先筛选,再处理
//偏函数
def f2:PartialFunction[Int,Int]={
case i:Int=>i*10}
def f3:PartialFunction[Any,Int]={
case i:Int=>i*10
case i:String=>0
}
val arr2=Array[Int](1,2,3,4)
val collect: Array[Int] =arr2.collect(f2)
println(collect)
println(collect.toBuffer)
val arr3=Array[Any](1,2,3,4,"Scala")
val collect2=arr3.collect(f3)
println(collect2.toBuffer)
[I@4b168fa9
ArrayBuffer(10, 20, 30, 40)
ArrayBuffer(10, 20, 30, 40, 0)