• Scala的高级用法


    1. 默认参数值

    1.1 方法默认参数

      def main(args: Array[String]): Unit = {
        //定义打印日志方法
        def log(date:Date,msg:String,level:String="Info"): Unit ={
          println(s"$date  $level $msg")
        }
        log(new Date,"你好");
        log(new Date(),"你好","Info");
        log(new Date(),"错误信息","Error");
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    默认值顺序在中间的调用加上命名参数才能调用,否则报错

    def log(date:Date,level:String="Info",msg:String): Unit ={
          println(s"$date  $level $msg")
        }
        log(new Date,msg="你好");
    
    • 1
    • 2
    • 3
    • 4

    1.2 类默认参数

     def main(args: Array[String]): Unit = {
        val point1 = new Point(y = 1)
        point1.printLocation()
      }
      class Point(val x: Double = 0, val y: Double = 0){
    
        def printLocation(): Unit ={
          print(s"x=$x  $y")
        }
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2. 特质 (Traits)

    用于在类 (Class)之间共享程序接口 (Interface)和字段 (Fields)。 它们类似于Java 8的接口。 类和对象 (Objects)可以扩展特质,但是特质不能被实例化,因此特质没有参数。

    2.1 子类型

    trait Animal {
      def say(): Unit ={
        println("animal say....")
      }
      def walk(): Unit ={
        println("animal walk....")
      }
    }
    //cat 继承animal
    class Cat extends Animal{
      def miaomiao(): Unit ={
        println("car miaomiao...")
      }
    }
    
    def main(args: Array[String]): Unit = {
      val cat=new Cat()
      cat.miaomiao()
      cat.walk()
      cat.say()
    }
    // car miaomiao...
    //animal walk....
    //animal say....
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    2.2 扩展特征,当做接口来使用

    //定义迭代器 使用泛型T
      trait Iterator[T] {
        def hasNext: Boolean
        def next(): T
      }
      //自定义实现的Int类型的迭代器
      class IntIterator(to: Int) extends Iterator[Int] {
        private var current = 0
        override def hasNext: Boolean = current < to
        override def next(): Int =  {
          if (hasNext) {
            val t = current
            current += 1
            t
          } else 0
        }
      }
    
      def main(args: Array[String]): Unit = {
        val intIterator = new IntIterator(5)
        while(intIterator.hasNext){
          println(intIterator.next())
        }
    //    0
    //    1
    //    2
    //    3
    //    4
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    3.元组

    元组是一个可以包含不同类型元素的类,元组是不可变的。
    经常用于函数返回多个值。
    元组包含2-22给个元素之间。

    3.1 定义与取值

     def main(args: Array[String]): Unit = {
        val t1 = Tuple1(1)
        //访问元素
        println(t1._1)
        val t2 = new Tuple1("asdas")
        println(t2._1)
        //也可以直接括号
        val t3=("as",12,false)
        //指定类型
        val t4=("as",12,true,0.88):Tuple4[String,Int,Boolean,Double]
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.2 元组用于模式匹配

    def main(args: Array[String]): Unit = {
        val courseScores = List(("Chinese", 77), ("Math", 100), ("Geo", 0 ),("English", 55 ))
        //遍历
        courseScores.foreach{ tuple => {
           tuple match {
             case p if(p._2 == 100) => println(s" ${p._1} score is 100")
             case p if(p._2 > 60 ) => println(s" ${p._1} score is greater than 60")
             case p if(p._2 == 0) => println(s" ${p._1} score is o")
             case _ => println(s"不及格")
          }
        }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3.3 用于for循环

    def main(args: Array[String]): Unit = {
        val numPairs = List((2, 5), (3, -7), (20, 56))
        for ((a, b) <- numPairs) {
          println(a * b)
        }
        ///10
        //-21
        //1120
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    4 高阶函数

    使用函数来作为参数或则返回结果。

    4.1 常见的高阶函数map

      def main(args: Array[String]): Unit = {
        var seqno = Seq(1,2,3)
        val values = seqno.map(x => x * x)
        for ( x <- values ){
          println(x )
        }
    //    1
    //    4
    //    9
    
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    4.2 简化涨薪策略代码

     //定义加薪的规则
      def smallPromotion(salaries: List[Double]): List[Double] =
        salaries.map(salary => salary * 1.2)
      //薪资的
      def greatPromotion(salaries: List[Double]): List[Double] =
        salaries.map(salary => salary * math.log(salary))
      //薪资
      def hugePromotion(salaries: List[Double]): List[Double] =
        salaries.map(salary => salary * salary)
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    去掉重复代码,定义一个方法接口,涨薪的规则传入函数

      def promotion(salaries: List[Double], promotionFunction: Double => Double): List[Double] = {
        salaries.map(promotionFunction)
      }
    
    • 1
    • 2
    • 3

    测试

    val salaries = List(2500.00,3000.00,4000.00)
      //实现涨薪
      var newsalaries= promotion(salaries,(x:Double) => x* 1.2)
      for(s <- newsalaries){
        print(s"$s ")
        //3000.0 3600.0 4800.0
      }
      println()
      println("-----------------------------")
      println()
      var newsalaries2= promotion(salaries,(x:Double) => x* x)
      for(s <- newsalaries2){
        print(s"$s ")
        //6250000.0 9000000.0 1.6E7 
      }
      
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    5.嵌套方法

    嵌套方法经常使用的就是递归调用。
    求阶乘

     //定义阶乘
        def fac(x:Int):Int = {
          if (x==1) {
            x
          }
          else {
            x * fac(x-1)
          }
        }
        //24
        print(fac(4))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6.多参数列表(柯里化

    方法可以定义多个参数列表,当使用较少的参数列表调用多参数列表的方法时,会产生一个新的函数,该函数接收剩余的参数列表作为其参数。这被称为柯里化

    def foldLeft[B](z: B)(op: (B, A) => B): B = {
        var acc = z
        var these: LinearSeq[A] = coll
        while (!these.isEmpty) {
          acc = op(acc, these.head)
          these = these.tail
        }
        acc
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    测试

     val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
        val res = numbers.foldLeft(0)((m, n) => m + n)
        print(res) // 55
    
    • 1
    • 2
    • 3

    7.模式匹配

    7.1 简单的模式匹配

    def main(args: Array[String]): Unit = {
        val x: Int = Random.nextInt(5)
       val str = x match {
          case 0 => "zero"
          case 1 => "one"
          case 2 => "two"
          case _ => "other"
        }
        println(str)
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    8.隐式转换

    方法可以具有 隐式 参数列表,由参数列表开头的 implicit 关键字标记。 如果参数列表中的参数没有像往常一样传递, Scala 将查看它是否可以获得正确类型的隐式值,如果可以,则自动传递。

    8.1 官网的列子

    //定义一个抽象类,提供两个方法一个add 一个unit
        abstract class Monoid[A] {
          def add(x: A, y: A): A
          def unit: A
        }
         //隐式实现字符串的拼接
          implicit val stringMonoid: Monoid[String] = new Monoid[String] {
            def add(x: String, y: String): String = x concat y
            def unit: String = ""
          }
          //隐式实现整型的数字相加
          implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
            def add(x: Int, y: Int): Int = x + y
            def unit: Int = 0
          }
          //传入一个list实现不同类型的累加
          def sum[A](xs: List[A])(
            implicit m: Monoid[A]): A =
            if (xs.isEmpty) m.unit
            else m.add(xs.head, sum(xs.tail))
    
          println(sum(List(1, 2, 3)))       // 6
          println(sum(List("a", "b", "c"))) //abc
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    完结,其他的可以到官网看看,用到在学。

  • 相关阅读:
    分类预测|基于贝叶斯优化长短期记忆网络的数据分类预测Matlab程序 多特征输入多类别输出 BO-LSTM 附赠预测新数据
    剑指 Offer 26. 树的子结构
    TypeScript必知三部曲(一)TypeScript编译方案以及IDE对TS的类型检查
    ae快捷键
    conda配置pytroch
    【ROS入门】机器人系统仿真——相关组件以及URDF集成Rviz
    rust 中 str 与 String; &str &String
    【Linux命令】用户和用户管理
    linux常用命令
    redis的详解和项目应用之SESSION共享
  • 原文地址:https://blog.csdn.net/qq_37400096/article/details/130418544