SCALA-DAY06

1 匹配模式

1.1字符串匹配

package com._51doit.day06.demo

import scala.util.Random

/**
 * FileName: CaseDEmo
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description: 
 */
object CaseDemo {
  def main(args: Array[String]): Unit = {

    val arr = Array[String]("java", "js", "sql", "scala")
    arr.map(e => e match {
      case "java" => "hls"
      case "js" => "sls"
      case "sql" => "cls"
      case "scala" => "zixue"
      case _ =>
    }).foreach(println)
    /* val index: Int = Random.nextInt(arr.length)
     val e: String = arr(index)
     val value: Any = e match {
       case "java" => "hls"
       case "js" => "sls"
       case "sql" => "cls"
       case "scala" => "zixue"
       case _ =>
     }*/
   // println(value)


  }


}

1.2 样例类

package com._51doit.day06.demo

/**
 * FileName: CaseDemo2
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006 
 * Description: 
 */
/*abstract class Animal
case class  Cat(name: String) extends Animal
case class  Dog(name: String) extends Animal
case class  Monkey(name: String) extends Animal*/

class CaseDemo2 {

  def opt(arg:Animal): String = arg match {
    case Cat(_) =>"cat"
    case Dog(_) =>"cat"
    case _ => "do not know"
  }

}

object CaseDemo2{
  def main(args: Array[String]): Unit = {
    val cd = new CaseDemo2
    println(cd.opt(Dog("小黑")))
  }

}


----------------------------------------------------------------------------------
package com._51doit.day06.demo

/**
 * FileName: CaseDemo3
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006 
 * Description: 
 */

abstract class Animal
case class  Cat(name: String) extends Animal
case class  Dog(name: String) extends Animal
case class  Monkey(name: String) extends Animal
object CaseDemo3 {
  def main(args: Array[String]): Unit = {
    val arr = Array[Animal](Dog("小黑"),Cat("小花"),Monkey("小空"))
    /*val arr2 = Array(1,2,"hello")
    arr2.map(e=>e match {
      case Int=> "int"
      case String => "string"
      case _ =>
    }).foreach(println)*/


    arr.map(e=>e match {
      case x:Cat =>"小花"
      case x:Dog =>"小黑"
      case x:Monkey =>"小空"
      case _ =>
    }).foreach(println)

    arr.map(e=>e match {
        // 匹配到指定的类
      case Cat(_) => e
      case Dog(_) =>"小黑2"
      case Monkey(_) =>"小空2"
      case _ =>
    }).foreach(println)

  }

}

----------------------------------------------------------------------------------
package com._51doit.day06.demo

import scala.util.Random

/**
 * FileName: CaseDemo4
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description: 
 */
case class User(val name:String , val age:Int)
object CaseDemo4 {
  def main(args: Array[String]): Unit = {

    val ls = List(User("a",11),User("b",21),User("c",31) , User("a",33))
    ls.map(e=>e match {
      case User("a",_) => e
      case _ =>User("a",Random.nextInt(30))
    }).foreach(println)

  }

}


1.3 option匹配

package com._51doit.day06.demo

/**
 * FileName: OptionCase
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description: 
 */
object OptionCase {
  def main(args: Array[String]): Unit = {
    val mp = Map[String, List[String]](
      "sl" -> List("fsy", "mj", "wk"),
      "wd" -> List("zsf", "syq", "lib")
    )
    val opt: Option[List[String]] = mp.get("wd")
    /*if(opt.isDefined){
      val ls: List[String] = opt.get
      println(ls)
    }*/
    println(opt match {
      case Some(v) => v+ "--"
    })

  }

}

2 隐式详解 

2.1 隐式变量

package com._51doit.day06.demo.impc

/**
 * FileName: Demo1
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description:
 * 隐式属性
 * 使用implicit 修饰的变量
 */
object Demo1 {
  /**
   * 隐式变量  定义的时候简建议指定数据类型
   */
  implicit val name:String = "zss"
  implicit val job:String = "coder"

  /**
   * 定义一个方法  两个参数列表
   * 参数列表一  字符串
   * 参数列表二  隐式参数
   *            在调用的时候可以传值
   *            也可以不传  不传的时候从上下文对象中区找对应类型的隐式变量 (只能有一个对应类型的)
   *                找到使用
   *                  找不到 报错  找到多个 报错
   * 如果需要多个隐式参数  都写在第二个参数列表中show(msg:String)(implicit x:String,y:Int)
   * 隐私参数列表类型不能重复
   * @param msg
   * @param x
   */
  def show(msg:String)(implicit x:String): Unit ={
    println(msg+x)
  }

  def main(args: Array[String]): Unit = {
    // 调用两个参数列表的方法  分别传入实参
    show("hello:")("ada") //hello:ada
    // 调用两个参数列表的方法  只传入第一个参数列表实参  后面的隐式参数列表不传值
    // 说明 第二个参数的实参是 定义的隐式参数值
   // show("hi: ") //hi: zss


  }

}
package com._51doit.day06.demo.impc

/**
 * FileName: Demo2
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006 
 * Description: 
 */
object Demo2 {
  implicit val s1: String = "hello"
  implicit val s2: Int = 23
  def show(msg: String)(implicit name: String, age: Int): Unit = {
    println(msg + name + age)
  }
  def main(args: Array[String]): Unit = {
    show("aaa")
  }

}
package com._51doit.day06.demo.impc

/**
 * FileName: Demo3
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description: 
 */
object Demo3 {
  // 导入外部的隐式变量
  import  MyImplicit._
  def opt(x:String)(implicit name:String): Unit ={
    print(x+"--"+name)
  }
  def main(args: Array[String]): Unit = {
    opt("abc")
  }
}
package com._51doit.day06.demo.impc

/**
 * FileName: MyImplicit
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description:
 * 声明隐式变量
 */
object MyImplicit {
   // 定义两个隐式变量
  implicit val name:String = "hello"
  implicit val age:Int = 22

}

2.2 隐式函数 

package com._51doit.day06.demo.impc_func
import   com._51doit.day06.demo.impc_var.MyImplicit.f2

/**
 * FileName: Demo1
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description:
 * 隐式方法
 * 隐式函数
 *     处理的数据类型 =>  返回值
 *  在定义方法的时候opt()    ()参数列表二 (implicit f:(String,String)=>String)
 *  当 调用自己的普通方法opt()  参数列表二不传  从上下文对象中找
 */
object Demo1 {
  /**
   * 隐式函数  普通的函数前面加上implicit
   * 处理 (String,String)=>String
   * 当有一个方法处理的是两个字符串  这个隐式方法就会被默认调用
   */
  def show(str1: String, str2: String)(implicit o:(String,String)=>String): String = {
     o(str1,str2)
  }

  def main(args: Array[String]): Unit = {
    println(show("abc", "cba"))
    println(show("abc", "cba"))
    println(show("abc", "cba"))
    //........




  }

}
package com._51doit.day06.demo.impc_var

import java.io.File

import scala.io.Source

/**
 * FileName: MyImplicit
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description:
 * 声明隐式变量
 */
object MyImplicit {
  // 隐式变量
  implicit val name1: String = "hello"
  implicit val name2: String = "hello2"
  implicit val age: Int = 22
  // 隐式函数
  implicit val f1 = (x1: String, x2: String) => {
    (x1 + x2).toUpperCase
  }
  implicit val f2 = (x1: String, x2: String) => {
    (x1 + x2 + "doit").toUpperCase
  }

  // 隐式类
  implicit class RichFile(file: File) {
    def getLines: Iterator[String] = {
      val lines: Iterator[String] = Source.fromFile(file).getLines()
      lines
    }

    def add(): Unit = {
    }
    def show(): Unit = {
    }
  }

}

2.3 隐式类 

方便增强某个类 

package com._51doit.day06.demo.impc_class

import java.io.File

import scala.io.Source

/**
 * FileName: MyImplicitClass
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description:
 * 隐式类是用来对一个类进行增强
 * new  File("").getLines
 *
 */
object MyImplicitClass {
  implicit  class RichFile(file:File){
    def  getLines: Iterator[String] ={
      val lines: Iterator[String] = Source.fromFile(file).getLines()
      lines
    }
    def add(): Unit ={
    }
    def show(): Unit ={
    }
  }
}
package com._51doit.day06.demo.impc_class

import java.io.File
import MyImplicitClass.RichFile

/**
 * FileName: Test1
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description:
 */
object Test1 {
  def main(args: Array[String]): Unit = {
    val file = new File("d://word.txt")
    // 偷偷的将隐式类中的方法合并到 File方法中
    val lines: Iterator[String] = file.getLines
    lines.foreach(println)
  }


}
package com._51doit.day06.demo.impc_class

/**
 * FileName: Demo
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description: 
 */
object Demo {

  /**
   * 柱构造器中有一个要增强的类
   */
  implicit class  MyAdvice(a:A){
    def a2(): Unit ={
      println("a2...")
    }
    def a3(): Unit ={
      println("a3...")
    }
    def a4(): Unit ={
      println("a4...")
    }

  }

  implicit class  MyAdvice2(a:A){

    def a22(): Unit ={
      println("a2...")
    }
    def a33(): Unit ={
      println("a3...")
    }
    def a44(): Unit ={
      println("a4...")
    }

  }
}
package com._51doit.day06.demo.impc_class
import com._51doit.day06.demo.impc_class.Demo._
/**
 * FileName: Test2
 * Author:   多易教育-DOIT
 * Date:     2020/11/6 0006
 * Description: 
 */
object Test2 {
  def main(args: Array[String]): Unit = {
    val a = new A
    a.a1()
    //-------
    a.a22()
    a.a33()
    a.a44()
    a.a2()
    a.a3()
    a.a4()

  }

}

猜你喜欢

转载自blog.csdn.net/qq_37933018/article/details/109527070