Scala高阶语法

打印 上一主题 下一主题

主题 858|帖子 858|积分 2574

高阶函数

函数可以作为参数进行传递和返回值进行返回
  1. //传一个a乘b 就返回一个函数,逻辑是实现两数相乘
  2. //传一个a*b 返回一个函数,逻辑是实现两数相乘
  3. //传一个axb 返回一个函数,逻辑是实现两数相乘
  4. def funTest6(str:String,fun:(String)=>Int):(Int,Int)=>Int = {
  5.   val i: Int = fun(str)
  6.   i match {
  7.     case 0 => (a,b)=>a+b
  8.     case 1 => (a,b)=>a-b
  9.     case 2 => (a,b)=>a*b
  10.     case 3 => (a,b)=>a/b
  11.   }
  12. }
  13. val function: (Int, Int) => Int = funTest6("a*b", (s) => {
  14.   if (s.contains("*") || s.contains("乘")) {
  15.     2
  16.   } else {
  17.     0
  18.   }
  19. })
  20. println(function(2, 3))
复制代码
匿名函数

没有名字的函数就是匿名函数。
例如:
  1. (x:Int)=>{函数体}
  2. x:表示输入参数类型;Int:表示输入参数类型;函数体:表示具体代码逻辑```
  3. 传递匿名函数至简原则:
  4. 1.        参数的类型可以省略,会根据形参进行自动的推导
  5. 2.        类型省略之后,发现只有一个参数,则圆括号可以省略;其他情况:没有参数和参数超过 1 的永远不能省略圆括号。
  6. 3.        匿名函数如果只有一行,则大括号也可以省略
  7. 4.        如果参数只出现一次,则参数省略且后面参数可以用_代替
  8. 练习1:传递的函数有一个参数
  9. 代码示例:
  10. ```Scala
  11. def main(args: Array[String]): Unit = {
  12. // (1)定义一个函数:参数包含数据和逻辑函数
  13. def operation(arr: Array[Int], op: Int => Int): Array[Int] = {
  14.   for (elem <- arr) yield op(elem)
  15. }
  16. // (2)定义逻辑函数
  17. def op(ele: Int): Int = {
  18. ele + 1
  19. }
  20. // (3)标准函数调用
  21. val arr = operation(Array(1, 2, 3, 4), op)
  22. println(arr.mkString(","))
  23. // (4)采用匿名函数
  24. val arr1 = operation(Array(1, 2, 3, 4), (ele: Int) => {
  25. ele + 1
  26. })
  27. println(arr1.mkString(","))
  28. // (4.1)参数的类型可以省略,会根据形参进行自动的推导;
  29. val arr2 = operation(Array(1, 2, 3, 4), (ele) => {
  30. ele + 1
  31. })
  32. println(arr2.mkString(","))
  33. // (4.2)类型省略之后,发现只有一个参数,则圆括号可以省略;其他情
  34. 况:没有参数和参数超过 1 的永远不能省略圆括号。
  35. val arr3 = operation(Array(1, 2, 3, 4), ele => {
  36. ele + 1
  37. })
  38. println(arr3.mkString(","))
  39. // (4.3) 匿名函数如果只有一行,则大括号也可以省略
  40. val arr4 = operation(Array(1, 2, 3, 4), ele => ele + 1)
  41. println(arr4.mkString(","))
  42. //(4.4)如果参数只出现一次,则参数省略且后面参数可以用_代替
  43. val arr5 = operation(Array(1, 2, 3, 4), _ + 1)
  44. println(arr5.mkString(","))
  45. }
  46. }
复制代码
练习二:传递的函数有两个参数
代码示例:
  1. object TestFunction {
  2. def main(args: Array[String]): Unit = {
  3. def calculator(a: Int, b: Int, op: (Int, Int) => Int): Int
  4. = {
  5. op(a, b)
  6. }
  7. // (1)标准版
  8. println(calculator(2, 3, (x: Int, y: Int) => {x + y}))
  9. // (2)如果只有一行,则大括号也可以省略
  10. println(calculator(2, 3, (x: Int, y: Int) => x + y))
  11. // (3)参数的类型可以省略,会根据形参进行自动的推导;
  12. println(calculator(2, 3, (x , y) => x + y))
  13. // (4)如果参数只出现一次,则参数省略且后面参数可以用_代替
  14. println(calculator(2, 3, _ + _))
  15. }
  16. }
复制代码
偏函数

偏函数是一个特质 ,用来专门处理某种数据类型! [注意可以同时处理多种数据类型]
偏函数的定义:
  1. val second: PartialFunction[List[Int], Option[Int]] = {
  2.      case x :: y :: _ => Some(y)
  3. }
复制代码
注:该偏函数的功能是返回输入的 List 集合的第二个元素
案例:将集合中的所有的Int类型的数据都加上1

代码示例:
  1. //  方式一   过滤器形式
  2. val list = List(1, 2, 3, 4, "hello")
  3. val res: List[Int] = list.filter(x => x.isInstanceOf[Int]).map(x => x.asInstanceOf[Int] + 1)
  4. res.foreach(println)
  5. // 方式二   匹配模式
  6. val res2: List[Any] = list.map(x => x match {
  7.    case x: Int => x + 1
  8.    case _ =>
  9.    })
  10. res2.filter(x => x.isInstanceOf[Int]).foreach(println)
  11. // 方式三  使用偏函数  泛型1 输入的数据类型 泛型2 要处理的数据类型
  12. val pp = new PartialFunction[Any,Int] {
  13.    // 返回true
  14.    override def isDefinedAt(x: Any) = {
  15.      x.isInstanceOf[Int]
  16.    }
  17.    // 执行下一个方法
  18.    override def apply(v1: Any) = {
  19.      v1.asInstanceOf[Int]+1
  20.    }
  21. }
  22.    //  list.map(pp).foreach(println)
  23.   list.collect(pp).foreach(println)
复制代码
偏函数原理

上述代码会被 scala 编译器翻译成以下代码,与普通函数相比,只是多了一个用于参数检查的函数——isDefinedAt,其返回值类型为 Boolean。
  1. val second = new PartialFunction[List[Int], Option[Int]] {
  2. //检查输入参数是否合格
  3. override def isDefinedAt(list: List[Int]): Boolean = list match
  4. {
  5. case x :: y :: _ => true
  6. case _ => false
  7. }
  8. //执行函数逻辑
  9. override def apply(list: List[Int]): Option[Int] = list match
  10. {
  11. case x :: y :: _ => Some(y)
  12. }
  13. }
复制代码
偏函数的执行流程


  • 遍历list中的每个元素
  • 调用 val e =  if (isDefinedAt) {apply}
  • 每得到一个e 就会将e存储在一个新的集合中返回使用偏函数就不要使用map方法了
偏函数的简写形式
  1. val list = List(2, 4, 6, 8, "cat")
  2. //定义一个偏函数
  3. def myPartialFunction: PartialFunction[Any, Int] = {
  4.   case x: Int => x * x
  5. }
  6. list.collect(myPartialFunction).foreach(println)
  7. // 简写方式
  8. list.collect({
  9.   case x:Int=>x*x
  10. }).foreach(println)
复制代码
偏函数总结


  • 使用构建特质的实现类(使用的方式是PartialFunction的匿名子类)
  • PartialFunction 是个特质(看源码)
  • 构建偏函数时,参数形式 [Any, Int]是泛型,第一个表示参数类型,第二个表示返回参数
  • 当使用偏函数时,会遍历集合的所有元素,编译器执行流程时先执行isDefinedAt()如果为true ,就会执行 apply, 构建一个新的Int 对象返回
  • 执行isDefinedAt() 为false 就过滤掉这个元素,即不构建新的Int对象.
  • map函数不支持偏函数,因为map底层的机制就是所有循环遍历,无法过滤处理原来集合的元素
  • collect函数支持偏函数
模式匹配

模式匹配语法中,采用 match 关键字声明,每个分支采用 case 关键字进行声明,当需要匹配时,会从第一个 case 分支开始,如果匹配成功,那么执行对应的逻辑代码,如果匹配不成功,继续执行下一个分支进行判断。如果所有 case 都不匹配,那么会执行 case _分支,类似于 Java 中 default 语句。
基本语法
  1. object TestMatchCase {
  2. def main(args: Array[String]): Unit = {
  3. var a: Int = 10
  4. var b: Int = 20
  5. var operator: Char = 'd'
  6. var result = operator match {
  7. case '+' => a + b
  8. case '-' => a - b
  9. case '*' => a * b
  10. case '/' => a / b
  11. case _ => "illegal"
  12.   }
  13. println(result)
  14. }
  15. }
复制代码
说明:

  • 如果所有 case 都不匹配,那么会执行 case _ 分支,类似于 Java 中 default 语句,若此时没有 case _ 分支,那么会抛出 MatchError。
  • 每个 case 中,不需要使用 break 语句,自动中断 case。
  • match case 语句可以匹配任何类型,而不只是字面量。
  • => 后面的代码块,直到下一个 case 语句之前的代码是作为一个整体执行,可以使用{}括起来,也可以不括。
模式守卫

如果想要表达匹配某个范围的数据,就需要在模式匹配中增加条件守卫。
代码演示:
  1. object TestMatchGuard {
  2. def main(args: Array[String]): Unit = {
  3. def abs(x: Int) = x match {
  4. case i: Int if i >= 0 => i
  5. case j: Int if j < 0 => -j
  6. case _ => "type illegal"
  7. }
  8. println(abs(-5))
  9. }
  10. }
复制代码
模式匹配类型

匹配常量

Scala 中,模式匹配可以匹配所有的字面量,包括字符串,字符,数字,布尔值等等
代码演示:
  1. object TestMatchVal {
  2. def main(args: Array[String]): Unit = {
  3. println(describe(6))
  4. }
  5. def describe(x: Any) = x match {
  6. case 5 => "Int five"
  7. case "hello" => "String hello"
  8. case true => "Boolean true"
  9. case '+' => "Char +"
  10. }
  11. }
复制代码
匹配类型

需要进行类型判断时,可以使用前文所学的 isInstanceOf[T]和 asInstanceOf[T],也可使用模式匹配实现同样的功能。
代码实现:
  1. object TestMatchClass {
  2. def describe(x: Any) = x match {
  3. case i: Int => "Int"
  4. case s: String => "String hello"
  5. case m: List[_] => "List"
  6. case c: Array[Int] => "Array[Int]"
  7. case someThing => "something else " + someThing
  8. }
  9. def main(args: Array[String]): Unit = {
  10.     println(describe(List(1, 2, 3, 4, 5)))
  11.     println(describe(Array(1, 2, 3, 4, 5, 6)))
  12.     println(describe(Array("abc")))
  13. }
  14. }
复制代码
匹配数组

scala 模式匹配可以对集合进行精确的匹配,例如匹配只有两个元素的、且第一个元素为 0 的数组
代码实现:
  1. object TestMatchArray {
  2. def main(args: Array[String]): Unit = {
  3. for (arr <- Array(Array(0), Array(1, 0), Array(0, 1, 0),
  4. Array(1, 1, 0), Array(1, 1, 0, 1), Array("hello", 90))) { // 对
  5. 一个数组集合进行遍历
  6. val result = arr match {
  7. case Array(0) => "0" //匹配 Array(0) 这个数组
  8. case Array(x, y) => x + "," + y //匹配有两个元素的数组,然后将将元素值赋给对应的 x,y
  9. case Array(0, _*) => "以 0 开头的数组" //匹配以 0 开头和
  10. 数组
  11. case _ => "something else"
  12. }
  13. println("result = " + result)
  14. }
  15. }
复制代码
匹配列表

方式一代码实现:
  1. object TestMatchList {
  2. def main(args: Array[String]): Unit = {
  3. //list 是一个存放 List 集合的数组
  4. //请思考,如果要匹配 List(88) 这样的只含有一个元素的列表,并原值返回.应该怎么写
  5. for (list <- Array(List(0), List(1, 0), List(0, 0, 0), List(1,
  6. 0, 0), List(88))) {
  7. val result = list match {
  8. case List(0) => "0" //匹配 List(0)
  9. case List(x, y) => x + "," + y //匹配有两个元素的 List
  10. case List(0, _*) => "0 ..."
  11. case _ => "something else"
  12. }
  13. println(result)
  14. }
  15. }
  16. }
复制代码
方式二代码实现:
  1. object TestMatchList {
  2. def main(args: Array[String]): Unit = {
  3. val list: List[Int] = List(1, 2, 5, 6, 7)
  4. list match {
  5. case first :: second :: rest => println(first + "-" +
  6. second + "-" + rest)
  7. case _ => println("something else")
  8.   }
  9. }
  10. }
复制代码
匹配元组

代码实现:
  1. object TestMatchTuple {
  2. def main(args: Array[String]): Unit = {
  3. //对一个元组集合进行遍历
  4. for (tuple <- Array((0, 1), (1, 0), (1, 1), (1, 0, 2))) {
  5. val result = tuple match {
  6. case (0, _) => "0 ..." //是第一个元素是 0 的元组
  7. case (y, 0) => "" + y + "0" // 匹配后一个元素是 0 的对偶元组
  8. case (a, b) => "" + a + " " + b
  9. case _ => "something else" //默认
  10. }
  11. println(result)
  12. }
  13. }
  14. }
复制代码
匹配对象及样例类

代码示例:
  1. class User(val name: String, val age: Int)
  2. object User{
  3. def apply(name: String, age: Int): User = new User(name, age)
  4. def unapply(user: User): Option[(String, Int)] = {
  5. if (user == null)
  6. None
  7. else
  8. Some(user.name, user.age)
  9. }
  10. }
  11. object TestMatchUnapply {
  12. def main(args: Array[String]): Unit = {
  13. val user: User = User("zhangsan", 11)
  14. val result = user match {
  15. case User("zhangsan", 11) => "yes"
  16. case _ => "no"
  17. }
  18. println(result)
  19. }
  20. }
复制代码
小结

  • 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]]
函数柯里化&闭包

闭包定义:

闭包:如果一个函数,访问到了它的外部(局部)变量的值,那么这个函数和他所处的环境,称为闭包
代码示例:
  1. package cn.doitedu.data_export
  2. import org.apache.commons.lang3.RandomUtils
  3. object CloseTest {
  4.   def main(args: Array[String]): Unit = {
  5.     val fx = (a:Int,b:Int)=>{
  6.       a+b
  7.     }
  8.     val fxx = (a:Int) => {
  9.       (b:Int)=>a+b
  10.     }
  11.     val res = fxx(3)(10)
  12.     val f = () => {
  13.       var p = RandomUtils.nextInt(1,10)
  14.       val inner = () => {
  15.         p += 1
  16.         p
  17.       }
  18.       inner
  19.     }
  20.     val x1= f()
  21.     println(x1())
  22.     println(x1())
  23.     println("-----------")
  24.     val x2 = f()
  25.     println(x2())
  26.     println(x2())
  27.     println(x2())
  28.   }
  29. }
复制代码
柯里划函数的定义:

函数柯里化:把一个参数列表的多个参数,变成多个参数列表。
意义: 方便数据的演变, 后面的参数可以借助前面的参数推演 , foldLeft的实现
有多个参数列表的函数就是柯里化函数,所谓的参数列表就是使用小括号括起来的函数参数列表
curry化最大的意义在于把多个参数的function等价转化成多个单参数function的级联,这样所有的函数就都统一了,方便做lambda演算。 在scala里,curry化对类型推演也有帮助,scala的类型推演是局部的,在同一个参数列表中后面的参数不能借助前面的参数类型进行推演,curry化以后,放在两个参数列表里,后面一个参数列表里的参数可以借助前面一个参数列表里的参数类型进行推演。这就是为什么 foldLeft这种函数的定义都是curry的形式
惰性加载

当函数返回值被声明为 lazy 时,函数的执行将被推迟,直到我们首次对此取值,该函数才会执行。这种函数我们称之为惰性函数。
代码示例:
  1. def main(args: Array[String]): Unit = {
  2. lazy val res = sum(10, 30)
  3. println("----------------")
  4. println("res=" + res)
  5. }
  6. def sum(n1: Int, n2: Int): Int = {
  7. println("sum 被执行。。。")
  8. return n1 + n2
  9. }
  10. 运行结果:
  11. ----------------
  12. sum 被执行。。。
  13. res=40
复制代码
注意:lazy 不能修饰 var 类型的变量
隐式转换

隐式函数

隐式转换可以在不需改任何代码的情况下,扩展某个类的功能
练习:通过隐式转化为 Int 类型增加方法。
  1. //创建一个隐式方法,在def 前面加上关键字 implicit  让一个类型具有更加丰富的功能
  2. implicit def stringWrapper(str:String)={
  3.   new MyRichString(str)
  4. }
  5. class MyRichString(val str:String){
  6.   def fly()={
  7.     println(str+",我是字符串,我能飞!!")
  8.   }
  9.   def jump()={
  10.     str + ":我能跳!"
  11.   }
  12. }
  13. package com.doit.day02
  14. import com.doit.day01.AnythingElse.Else._
  15. /**
  16. * 隐式转换:说白了就是给一个函数,参数,类 赋予更加强大的功能
  17. */
  18. object _10_隐式转换 {
  19.   def main(args: Array[String]): Unit = {
  20.     //1 本身是int 类型的,但是他却可以调用richInt这个类里面的方法
  21.     /**
  22.      *  implicit def intWrapper(x: Int)= {
  23.      *  //相当于创建了一个 RichInt的对象
  24.      *    new runtime.RichInt(x)
  25.      *  }
  26.      *  我写了一个隐式方法,传进去一个参数,返回给我的是一个对象, 并且在这个方法最前面加上了implicit 关键字 ,那么
  27.      *  这个参数的类型 就具备了该类的方法
  28.      */
  29.     val str: String = "zss"
  30.     str.fly()
  31.   }
  32. }
复制代码
隐式参数

普通方法或者函数中的参数可以通过 implicit 关键字声明为隐式参数,调用该方法时,
就可以传入该参数,编译器会在相应的作用域寻找符合条件的隐式值
说明:

  • 同一个作用域中,相同类型的隐式值只能有一个
  • 编译器按照隐式参数的类型去寻找对应类型的隐式值,与隐式值的名称无关。
  • 隐式参数优先于默认参数
代码示例:
  1. //定义了一个方法,方法中的参数设置的是隐式参数
  2. def add(implicit a: Int, b: String) = {
  3.   a + b.toInt
  4. }
  5. //定义两个变量,前面用implicit  修饰  变成隐式的
  6. implicit val a:Int = 10
  7. implicit val b:String = "20"
  8. //调用方法的时候,如果没有传参数,那么他会去上下文中找是否又隐式参数,如果有
  9. //他就自己偷偷的传进去了,如果没有,会直接报错
  10. add
复制代码
隐式类

在 Scala2.10 后提供了隐式类,可以使用 implicit 声明类,隐式类的非常强大,同样可
以扩展类的功能,在集合中隐式类会发挥重要的作用。
说明:

  • 其所带的构造参数有且只能有一个
  • 隐式类必须被定义在“类”或“伴生对象”或“包对象”里,即隐式类不能是顶级的。
代码示例:
  1. implicit class snake(ant:Ant){
  2.   def eatElephant()={
  3.     println("i can eat elephant!!")
  4.   }
  5. }
  6. val ant: Ant = new Ant
  7. ant.eatElephant()
复制代码
隐式解析机制


  • 首先会在当前代码作用域下查找隐式实体(隐式方法、隐式类、隐式对象)。
  • 如果第一条规则查找隐式实体失败,会继续在隐式参数的类型的作用域里查找。类型的作用域是指与该类型相关联的全部伴生对象以及该类型所在包的包对象。
代码示例:
  1. package com.chapter10
  2. import com.chapter10.Scala05_Transform4.Teacher
  3. //(2)如果第一条规则查找隐式实体失败,会继续在隐式参数的类型的作用域里查找。
  4. 类型的作用域是指与该类型相关联的全部伴生模块,
  5. object TestTransform extends PersonTrait {
  6. def main(args: Array[String]): Unit = {
  7. //(1)首先会在当前代码作用域下查找隐式实体
  8. val teacher = new Teacher()
  9. teacher.eat()
  10. teacher.say()
  11. }
  12. class Teacher {
  13. def eat(): Unit = {
  14. println("eat...")
  15. }
  16. }
  17. }
  18. trait PersonTrait {
  19. }
  20. object PersonTrait {
  21. // 隐式类 : 类型 1 => 类型 2
  22. implicit class Person5(user:Teacher) {
  23. def say(): Unit = {
  24. println("say...")
  25. }
  26. }
  27. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

曹旭辉

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表