高阶函数
函数可以作为参数进行传递和返回值进行返回
- //传一个a乘b 就返回一个函数,逻辑是实现两数相乘
- //传一个a*b 返回一个函数,逻辑是实现两数相乘
- //传一个axb 返回一个函数,逻辑是实现两数相乘
- def funTest6(str:String,fun:(String)=>Int):(Int,Int)=>Int = {
- val i: Int = fun(str)
- i match {
- case 0 => (a,b)=>a+b
- case 1 => (a,b)=>a-b
- case 2 => (a,b)=>a*b
- case 3 => (a,b)=>a/b
- }
- }
- val function: (Int, Int) => Int = funTest6("a*b", (s) => {
- if (s.contains("*") || s.contains("乘")) {
- 2
- } else {
- 0
- }
- })
- println(function(2, 3))
复制代码 匿名函数
没有名字的函数就是匿名函数。
例如:- (x:Int)=>{函数体}
- x:表示输入参数类型;Int:表示输入参数类型;函数体:表示具体代码逻辑```
- 传递匿名函数至简原则:
- 1. 参数的类型可以省略,会根据形参进行自动的推导
- 2. 类型省略之后,发现只有一个参数,则圆括号可以省略;其他情况:没有参数和参数超过 1 的永远不能省略圆括号。
- 3. 匿名函数如果只有一行,则大括号也可以省略
- 4. 如果参数只出现一次,则参数省略且后面参数可以用_代替
- 练习1:传递的函数有一个参数
- 代码示例:
- ```Scala
- def main(args: Array[String]): Unit = {
- // (1)定义一个函数:参数包含数据和逻辑函数
- def operation(arr: Array[Int], op: Int => Int): Array[Int] = {
- for (elem <- arr) yield op(elem)
- }
- // (2)定义逻辑函数
- def op(ele: Int): Int = {
- ele + 1
- }
- // (3)标准函数调用
- val arr = operation(Array(1, 2, 3, 4), op)
- println(arr.mkString(","))
-
-
- // (4)采用匿名函数
- val arr1 = operation(Array(1, 2, 3, 4), (ele: Int) => {
- ele + 1
- })
- println(arr1.mkString(","))
-
-
-
- // (4.1)参数的类型可以省略,会根据形参进行自动的推导;
- val arr2 = operation(Array(1, 2, 3, 4), (ele) => {
- ele + 1
- })
- println(arr2.mkString(","))
-
-
-
- // (4.2)类型省略之后,发现只有一个参数,则圆括号可以省略;其他情
- 况:没有参数和参数超过 1 的永远不能省略圆括号。
- val arr3 = operation(Array(1, 2, 3, 4), ele => {
- ele + 1
- })
- println(arr3.mkString(","))
-
-
-
- // (4.3) 匿名函数如果只有一行,则大括号也可以省略
- val arr4 = operation(Array(1, 2, 3, 4), ele => ele + 1)
- println(arr4.mkString(","))
- //(4.4)如果参数只出现一次,则参数省略且后面参数可以用_代替
- val arr5 = operation(Array(1, 2, 3, 4), _ + 1)
- println(arr5.mkString(","))
-
- }
- }
复制代码 练习二:传递的函数有两个参数
代码示例:- object TestFunction {
- def main(args: Array[String]): Unit = {
- def calculator(a: Int, b: Int, op: (Int, Int) => Int): Int
- = {
- op(a, b)
- }
- // (1)标准版
- println(calculator(2, 3, (x: Int, y: Int) => {x + y}))
- // (2)如果只有一行,则大括号也可以省略
- println(calculator(2, 3, (x: Int, y: Int) => x + y))
- // (3)参数的类型可以省略,会根据形参进行自动的推导;
- println(calculator(2, 3, (x , y) => x + y))
- // (4)如果参数只出现一次,则参数省略且后面参数可以用_代替
- println(calculator(2, 3, _ + _))
- }
- }
复制代码 偏函数
偏函数是一个特质 ,用来专门处理某种数据类型! [注意可以同时处理多种数据类型]
偏函数的定义:
- val second: PartialFunction[List[Int], Option[Int]] = {
- case x :: y :: _ => Some(y)
- }
复制代码注:该偏函数的功能是返回输入的 List 集合的第二个元素
案例:将集合中的所有的Int类型的数据都加上1
代码示例:- // 方式一 过滤器形式
- val list = List(1, 2, 3, 4, "hello")
- val res: List[Int] = list.filter(x => x.isInstanceOf[Int]).map(x => x.asInstanceOf[Int] + 1)
- res.foreach(println)
-
- // 方式二 匹配模式
- val res2: List[Any] = list.map(x => x match {
- case x: Int => x + 1
- case _ =>
- })
- res2.filter(x => x.isInstanceOf[Int]).foreach(println)
-
- // 方式三 使用偏函数 泛型1 输入的数据类型 泛型2 要处理的数据类型
- val pp = new PartialFunction[Any,Int] {
- // 返回true
- override def isDefinedAt(x: Any) = {
- x.isInstanceOf[Int]
- }
- // 执行下一个方法
- override def apply(v1: Any) = {
- v1.asInstanceOf[Int]+1
- }
- }
-
- // list.map(pp).foreach(println)
- list.collect(pp).foreach(println)
复制代码 偏函数原理
上述代码会被 scala 编译器翻译成以下代码,与普通函数相比,只是多了一个用于参数检查的函数——isDefinedAt,其返回值类型为 Boolean。- val second = new PartialFunction[List[Int], Option[Int]] {
- //检查输入参数是否合格
- override def isDefinedAt(list: List[Int]): Boolean = list match
- {
- case x :: y :: _ => true
- case _ => false
- }
- //执行函数逻辑
- override def apply(list: List[Int]): Option[Int] = list match
- {
- case x :: y :: _ => Some(y)
- }
- }
复制代码 偏函数的执行流程
- 遍历list中的每个元素
- 调用 val e = if (isDefinedAt) {apply}
- 每得到一个e 就会将e存储在一个新的集合中返回使用偏函数就不要使用map方法了
偏函数的简写形式
- val list = List(2, 4, 6, 8, "cat")
- //定义一个偏函数
- def myPartialFunction: PartialFunction[Any, Int] = {
- case x: Int => x * x
- }
- list.collect(myPartialFunction).foreach(println)
- // 简写方式
- list.collect({
- case x:Int=>x*x
- }).foreach(println)
复制代码 偏函数总结
- 使用构建特质的实现类(使用的方式是PartialFunction的匿名子类)
- PartialFunction 是个特质(看源码)
- 构建偏函数时,参数形式 [Any, Int]是泛型,第一个表示参数类型,第二个表示返回参数
- 当使用偏函数时,会遍历集合的所有元素,编译器执行流程时先执行isDefinedAt()如果为true ,就会执行 apply, 构建一个新的Int 对象返回
- 执行isDefinedAt() 为false 就过滤掉这个元素,即不构建新的Int对象.
- map函数不支持偏函数,因为map底层的机制就是所有循环遍历,无法过滤处理原来集合的元素
- collect函数支持偏函数
模式匹配
模式匹配语法中,采用 match 关键字声明,每个分支采用 case 关键字进行声明,当需要匹配时,会从第一个 case 分支开始,如果匹配成功,那么执行对应的逻辑代码,如果匹配不成功,继续执行下一个分支进行判断。如果所有 case 都不匹配,那么会执行 case _分支,类似于 Java 中 default 语句。
基本语法
- object TestMatchCase {
- def main(args: Array[String]): Unit = {
- var a: Int = 10
- var b: Int = 20
- var operator: Char = 'd'
- var result = operator match {
- case '+' => a + b
- case '-' => a - b
- case '*' => a * b
- case '/' => a / b
- case _ => "illegal"
- }
- println(result)
- }
- }
复制代码 说明:
- 如果所有 case 都不匹配,那么会执行 case _ 分支,类似于 Java 中 default 语句,若此时没有 case _ 分支,那么会抛出 MatchError。
- 每个 case 中,不需要使用 break 语句,自动中断 case。
- match case 语句可以匹配任何类型,而不只是字面量。
- => 后面的代码块,直到下一个 case 语句之前的代码是作为一个整体执行,可以使用{}括起来,也可以不括。
模式守卫
如果想要表达匹配某个范围的数据,就需要在模式匹配中增加条件守卫。
代码演示:- object TestMatchGuard {
- def main(args: Array[String]): Unit = {
- def abs(x: Int) = x match {
- case i: Int if i >= 0 => i
- case j: Int if j < 0 => -j
- case _ => "type illegal"
- }
- println(abs(-5))
- }
- }
复制代码 模式匹配类型
匹配常量
Scala 中,模式匹配可以匹配所有的字面量,包括字符串,字符,数字,布尔值等等
代码演示:- object TestMatchVal {
- def main(args: Array[String]): Unit = {
- println(describe(6))
- }
- def describe(x: Any) = x match {
- case 5 => "Int five"
- case "hello" => "String hello"
- case true => "Boolean true"
- case '+' => "Char +"
- }
- }
复制代码 匹配类型
需要进行类型判断时,可以使用前文所学的 isInstanceOf[T]和 asInstanceOf[T],也可使用模式匹配实现同样的功能。
代码实现:- object TestMatchClass {
- def describe(x: Any) = x match {
- case i: Int => "Int"
- case s: String => "String hello"
- case m: List[_] => "List"
- case c: Array[Int] => "Array[Int]"
- case someThing => "something else " + someThing
- }
- def main(args: Array[String]): Unit = {
- println(describe(List(1, 2, 3, 4, 5)))
- println(describe(Array(1, 2, 3, 4, 5, 6)))
- println(describe(Array("abc")))
- }
- }
复制代码 匹配数组
scala 模式匹配可以对集合进行精确的匹配,例如匹配只有两个元素的、且第一个元素为 0 的数组
代码实现:- object TestMatchArray {
- def main(args: Array[String]): Unit = {
- for (arr <- Array(Array(0), Array(1, 0), Array(0, 1, 0),
- Array(1, 1, 0), Array(1, 1, 0, 1), Array("hello", 90))) { // 对
- 一个数组集合进行遍历
- val result = arr match {
- case Array(0) => "0" //匹配 Array(0) 这个数组
- case Array(x, y) => x + "," + y //匹配有两个元素的数组,然后将将元素值赋给对应的 x,y
- case Array(0, _*) => "以 0 开头的数组" //匹配以 0 开头和
- 数组
- case _ => "something else"
- }
- println("result = " + result)
- }
- }
复制代码 匹配列表
方式一代码实现:- object TestMatchList {
- def main(args: Array[String]): Unit = {
- //list 是一个存放 List 集合的数组
- //请思考,如果要匹配 List(88) 这样的只含有一个元素的列表,并原值返回.应该怎么写
- for (list <- Array(List(0), List(1, 0), List(0, 0, 0), List(1,
- 0, 0), List(88))) {
- val result = list match {
- case List(0) => "0" //匹配 List(0)
- case List(x, y) => x + "," + y //匹配有两个元素的 List
- case List(0, _*) => "0 ..."
- case _ => "something else"
- }
- println(result)
- }
- }
- }
复制代码 方式二代码实现:- object TestMatchList {
- def main(args: Array[String]): Unit = {
- val list: List[Int] = List(1, 2, 5, 6, 7)
- list match {
- case first :: second :: rest => println(first + "-" +
- second + "-" + rest)
- case _ => println("something else")
- }
- }
- }
复制代码 匹配元组
代码实现:- object TestMatchTuple {
- def main(args: Array[String]): Unit = {
- //对一个元组集合进行遍历
- for (tuple <- Array((0, 1), (1, 0), (1, 1), (1, 0, 2))) {
- val result = tuple match {
- case (0, _) => "0 ..." //是第一个元素是 0 的元组
- case (y, 0) => "" + y + "0" // 匹配后一个元素是 0 的对偶元组
- case (a, b) => "" + a + " " + b
- case _ => "something else" //默认
- }
- println(result)
- }
- }
- }
复制代码 匹配对象及样例类
代码示例:- class User(val name: String, val age: Int)
- object User{
- def apply(name: String, age: Int): User = new User(name, age)
- def unapply(user: User): Option[(String, Int)] = {
- if (user == null)
- None
- else
- Some(user.name, user.age)
- }
- }
- object TestMatchUnapply {
- def main(args: Array[String]): Unit = {
- val user: User = User("zhangsan", 11)
- val result = user match {
- case User("zhangsan", 11) => "yes"
- case _ => "no"
- }
- println(result)
- }
- }
复制代码 小结
- val user = User("zhangsan",11),该语句在执行时,实际调用的是 User 伴生对象中的apply 方法,因此不用 new 关键字就能构造出相应的对象。
- 当将 User("zhangsan", 11)写在 case 后时[case User("zhangsan", 11) => "yes"],会默认调用 unapply 方法(对象提取器),user 作为 unapply 方法的参数,unapply 方法将 user 对象的 name 和 age 属性提取出来,与 User("zhangsan", 11)中的属性值进行匹配
- case 中对象的 unapply 方法(提取器)返回 Some,且所有属性均一致,才算匹配成功,属性不一致,或返回 None,则匹配失败。
- 若只提取对象的一个属性,则提取器为 unapply(obj:Obj):Option[T],若提取对象的多个属性,则提取器为 unapply(obj:Obj):Option[(T1,T2,T3…)],若提取对象的可变个属性,则提取器为 unapplySeq(obj:Obj):Option[Seq[T]]
函数柯里化&闭包
闭包定义:
闭包:如果一个函数,访问到了它的外部(局部)变量的值,那么这个函数和他所处的环境,称为闭包
代码示例:- package cn.doitedu.data_export
- import org.apache.commons.lang3.RandomUtils
- object CloseTest {
- def main(args: Array[String]): Unit = {
- val fx = (a:Int,b:Int)=>{
- a+b
- }
- val fxx = (a:Int) => {
- (b:Int)=>a+b
- }
- val res = fxx(3)(10)
- val f = () => {
- var p = RandomUtils.nextInt(1,10)
- val inner = () => {
- p += 1
- p
- }
- inner
- }
- val x1= f()
- println(x1())
- println(x1())
- println("-----------")
- val x2 = f()
- println(x2())
- println(x2())
- println(x2())
- }
- }
复制代码 柯里划函数的定义:
函数柯里化:把一个参数列表的多个参数,变成多个参数列表。
意义: 方便数据的演变, 后面的参数可以借助前面的参数推演 , foldLeft的实现
有多个参数列表的函数就是柯里化函数,所谓的参数列表就是使用小括号括起来的函数参数列表
curry化最大的意义在于把多个参数的function等价转化成多个单参数function的级联,这样所有的函数就都统一了,方便做lambda演算。 在scala里,curry化对类型推演也有帮助,scala的类型推演是局部的,在同一个参数列表中后面的参数不能借助前面的参数类型进行推演,curry化以后,放在两个参数列表里,后面一个参数列表里的参数可以借助前面一个参数列表里的参数类型进行推演。这就是为什么 foldLeft这种函数的定义都是curry的形式
惰性加载
当函数返回值被声明为 lazy 时,函数的执行将被推迟,直到我们首次对此取值,该函数才会执行。这种函数我们称之为惰性函数。
代码示例:- def main(args: Array[String]): Unit = {
- lazy val res = sum(10, 30)
- println("----------------")
- println("res=" + res)
- }
- def sum(n1: Int, n2: Int): Int = {
- println("sum 被执行。。。")
- return n1 + n2
- }
- 运行结果:
- ----------------
- sum 被执行。。。
- res=40
复制代码注意:lazy 不能修饰 var 类型的变量
隐式转换
隐式函数
隐式转换可以在不需改任何代码的情况下,扩展某个类的功能
练习:通过隐式转化为 Int 类型增加方法。- //创建一个隐式方法,在def 前面加上关键字 implicit 让一个类型具有更加丰富的功能
- implicit def stringWrapper(str:String)={
- new MyRichString(str)
- }
- class MyRichString(val str:String){
- def fly()={
- println(str+",我是字符串,我能飞!!")
- }
- def jump()={
- str + ":我能跳!"
- }
- }
- package com.doit.day02
- import com.doit.day01.AnythingElse.Else._
- /**
- * 隐式转换:说白了就是给一个函数,参数,类 赋予更加强大的功能
- */
- object _10_隐式转换 {
- def main(args: Array[String]): Unit = {
- //1 本身是int 类型的,但是他却可以调用richInt这个类里面的方法
- /**
- * implicit def intWrapper(x: Int)= {
- * //相当于创建了一个 RichInt的对象
- * new runtime.RichInt(x)
- * }
- * 我写了一个隐式方法,传进去一个参数,返回给我的是一个对象, 并且在这个方法最前面加上了implicit 关键字 ,那么
- * 这个参数的类型 就具备了该类的方法
- */
- val str: String = "zss"
- str.fly()
- }
- }
复制代码 隐式参数
普通方法或者函数中的参数可以通过 implicit 关键字声明为隐式参数,调用该方法时,
就可以传入该参数,编译器会在相应的作用域寻找符合条件的隐式值
说明:
- 同一个作用域中,相同类型的隐式值只能有一个
- 编译器按照隐式参数的类型去寻找对应类型的隐式值,与隐式值的名称无关。
- 隐式参数优先于默认参数
代码示例:- //定义了一个方法,方法中的参数设置的是隐式参数
- def add(implicit a: Int, b: String) = {
- a + b.toInt
- }
- //定义两个变量,前面用implicit 修饰 变成隐式的
- implicit val a:Int = 10
- implicit val b:String = "20"
- //调用方法的时候,如果没有传参数,那么他会去上下文中找是否又隐式参数,如果有
- //他就自己偷偷的传进去了,如果没有,会直接报错
- add
复制代码 隐式类
在 Scala2.10 后提供了隐式类,可以使用 implicit 声明类,隐式类的非常强大,同样可
以扩展类的功能,在集合中隐式类会发挥重要的作用。
说明:
- 其所带的构造参数有且只能有一个
- 隐式类必须被定义在“类”或“伴生对象”或“包对象”里,即隐式类不能是顶级的。
代码示例:- implicit class snake(ant:Ant){
- def eatElephant()={
- println("i can eat elephant!!")
- }
- }
- val ant: Ant = new Ant
- ant.eatElephant()
复制代码 隐式解析机制
- 首先会在当前代码作用域下查找隐式实体(隐式方法、隐式类、隐式对象)。
- 如果第一条规则查找隐式实体失败,会继续在隐式参数的类型的作用域里查找。类型的作用域是指与该类型相关联的全部伴生对象以及该类型所在包的包对象。
代码示例:- package com.chapter10
- import com.chapter10.Scala05_Transform4.Teacher
- //(2)如果第一条规则查找隐式实体失败,会继续在隐式参数的类型的作用域里查找。
- 类型的作用域是指与该类型相关联的全部伴生模块,
- object TestTransform extends PersonTrait {
- def main(args: Array[String]): Unit = {
- //(1)首先会在当前代码作用域下查找隐式实体
- val teacher = new Teacher()
- teacher.eat()
- teacher.say()
- }
- class Teacher {
- def eat(): Unit = {
- println("eat...")
- }
- }
- }
- trait PersonTrait {
- }
- object PersonTrait {
- // 隐式类 : 类型 1 => 类型 2
- implicit class Person5(user:Teacher) {
- def say(): Unit = {
- println("say...")
- }
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |