1. 程式人生 > >Scala學習第三天

Scala學習第三天

模式匹配

    java:對一個值進行條件判斷,針對不同條件進行不同處理。(switch)。

    scala:

變數 match {
    case value1 => 程式碼1
    case value2 => 程式碼2
    ......
    case _ => 程式碼n
}

    demo:

val names = Array("Steve Jobs","James Gosling","Jack Ma")
  val name = names(Random.nextInt(names.length))
  name match {
    case "Steve Jobs" => println("蘋果")
    case "Jack Ma" => println("阿里巴巴")
    case _ => println("不知道")
  }

加條件進行匹配:

def getGrade(name:String,grade:String):Unit={
    grade match{
      case "A" => println("perfect...")
      case "B" => println("so so...")
      case "C" => println("bad...")
      case _ if(name == "wjy") => println(name + ",you are a good boy,but...")
      case _ => println("不知道")
    }
  }

陣列模式匹配:

def getArray(array:Array[String]):Unit = {
    array match {
      case Array("wang") => println("Hi:wang")
      case Array("wang",_*) => println("Hi:wang,and other people...")
      case Array(x,y) => println("Hi:" + x + "," + y)
      case _ => println("i don't know...")
    }
  }

集合模式匹配:

def getList(list:List[String]):Unit = {
    list match{
      case "wjy" :: Nil => println("Hi:wjy")
//      case "wjy" :: tail => println("Hi:wjy and other people...")
      case x :: y :: z :: Nil => println("Hi:" + x + "," + y + "," + z)
      case _ => println("i don't know...")
    }
  }

型別模式匹配:

def matchType(obj:Any):Unit = {
    obj match {
      case x:Int => println("Int")
      case y:String => println("String")
      case m:Map[_,_] => println("Map")
      case _ => println("Other")
    }
  }

case class模式匹配:

class Person
  case class CTO(name:String,floor:Int) extends Person
  case class Employee(name:String,floor:Int) extends Person
  case class Other(name:String,floor:Int) extends Person

  def matchCaseClass(person:Person):Unit = {
    person match{
      case CTO(name,floor) => println("CTO:" + name + "," + floor)
      case Employee(name,floor) => println("Employee:" + name + "," + floor)
      case Other(name,floor) => println("Other:" + name + "," + floor)
    }
  }

some&none模式匹配:

val map = Map("wjy" -> 99,"cxr" -> 98)
  def getGrade(name:String):Unit = {
    val grade = map.get(name)
    grade match {
      case Some(grade) => println(name + ",your grade is " + grade)
      case None => println("Sorry...")
    }
  }

異常處理

try{
    val i = 1/0
    println(i)
  }catch {
    case e:Exception => println(e.getMessage)
  }

高階函式

字串高階操作

val name = "wjy"
  val sex = "男"
  println(s"$name 的性別是$sex")

  val context =
    """
      |這是一個多行字串
      |hello
      |wjy
    """.stripMargin
  println(context)

匿名函式

def add = (x:Int,y:Int) => x + y
  println(add(1,2))

curry柯里化函式

def add(x:Int,y:Int) = x+y
  println(add(2,3))

  //將原來接收兩個引數的一個函式,轉換成兩個
  def add1(x:Int)(y:Int) = x + y
  println(add1(2)(3))

高階函式操作

val list = List(1,2,3,4,5,6,7,8,9)
  //map
  list.map((x:Int) => x + 1).foreach(println)
  list.map(x => x + 1).foreach(println)
  list.map(_ + 1).foreach(println)

  //filter
  list.filter(_ > 8).foreach(println)// 9

  //take
  list.take(5).foreach(println)// 1 2 3 4 5

  //reduce
  println(list.reduce(_ + _))// 45

  //flatten
  val l = List(List(1,2),List(3,4),List(5,6))
  l.flatten.foreach(println) // 1 2 3 4 5 6 7 8 9

  //flatMap
  l.flatMap(_.map(_ + 1)).foreach(println)// 2 3 4 5 6 7

偏函式

被包在花括號內沒有match的一組case語句

def sayChinese:PartialFunction[String,String] = {
    case "w" => "小王"
    case "c" => "小陳"
    case _ => "不知道。。。"
  }

隱式轉換

object ImplicitDemo {
  def main(args: Array[String]): Unit = {
    //要讓person能夠擁有fly的功能,隱式轉換
    implicit def PersonToSuperman(person:Person):Superman = new Superman(person.name)
    val person1 = new Person("wjy")
    person1.fly()

  }
}
class Person(val name:String){
  def say():Unit = {
    println(s"$name say hello...")
  }
}
class Superman(val name:String){
  def fly():Unit = {
    println(s"$name can fly...")
  }
}

demo:

object ImplicitDemo {
  def main(args: Array[String]): Unit = {
    //要讓java.io.File擁有read()的功能,直接讀取檔案內容
    implicit def FileToRichFile(file:File):RichFile = new RichFile(file)
    val file = new File("D:\\test.txt")
    println(file.read())
  }
}
class RichFile(val file:File){
  def read():String = {
    scala.io.Source.fromFile(file).mkString
  }
}

隱式轉換封裝起來:

只需要在上面import匯入就行了

Scala操作資料庫

導包

<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
</dependency>

demo

object MysqlDemo extends App {
  // 1.引入依賴
  // 2.定義
  val driver = "com.mysql.jdbc.Driver"
  val url = "jdbc:mysql://localhost:3306/mysql"
  val userName = "root"
  val password = "123456"

  var connection:Connection = null
  try{

    classOf[com.mysql.jdbc.Driver]

    connection = DriverManager.getConnection(url,userName,password)

    val statement = connection.createStatement()
    val resultSet = statement.executeQuery("select * from user")
    while (resultSet.next()){
      val host = resultSet.getString("host")
      val user = resultSet.getString("user")
      println(s"$host,$user")
    }
  }catch {
    case e:Exception => e.printStackTrace()
  }finally {
    if (connection == null) connection.close()
  }

}