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()
  }

}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值