1. 程式人生 > >[Scala06]Scala中模式匹配、異常處理、高階函式、偏函式、隱式轉換

[Scala06]Scala中模式匹配、異常處理、高階函式、偏函式、隱式轉換

1、模式匹配

變數 match{

case 值1 => 程式碼1

case 值2 => 程式碼2

case 值3 => 程式碼3

case _=> 程式碼1

}

示例1:

def judgeGrade(name:String,grade:String):Unit= {

grade match{

case "A" => println("Excellent.....")

case "B" => println("Good")

case "C" => println("Just so so.....")

case if name="dove" => println(s"$name you are a good boy")

case _ => println("you need to work harder")

}

}

judgrade("zhangsan","D")   you need to work harder

judgeGrade("dove","d")  dove you are a good boy

示例2:根據陣列匹配

scala> def greeting(array:Array[String]):Unit={
     | array match{
     | case Array("dove") =>println("hi,dove")
     | case Array(x,y) =>println("hello,"+x+","+y)
     | case Array("xiaoyiba",_*) =>println("xiaoyiba and others")
     | case _ =>println("hi,everyone")
     | }}
greeting: (array: Array[String])Unit


scala> greeting(Array("dove"))
hi,dove


scala> greeting(Array("dove","zhangsan"))
hello,dove,zhangsan


scala> greeting(Array("xiaoyiba","zhangsan"))
hello,xiaoyiba,zhangsan


scala> greeting(Array("xiaoyiba","zhangsan","lisi"))
xiaoyiba and others


scala> greeting(Array("Lucy"))

hi,everyone

示例3:根據集合匹配

scala> def greeting(list:List[String]):Unit={
     | list match{
     | case "dove"::Nil => println("hi,dove")
     | case x::y::Nil => println("hello,"+x+","+y)
     | case "dove"::tail => println("hi,dove and others....")
     | case _ => println("hi,everyone")
     | }}

greeting: (list: List[String])Unit



scala> greeting(List("dove"))
hi,dove


scala> greeting(List("dove","Lucy"))
hello,dove,Lucy


scala> greeting(List("dove","Lucy","Jack"))
hi,dove and others....


scala> greeting(List("dove","Lucy","Jack","Lily"))
hi,dove and others....


scala> greeting(List("Lucy","Jack","Lily"))

hi,everyone

示例4:型別匹配

scala> def matchType(obj:Any):Unit={
     | obj match{
     | case x:Int =>println("Int")
     | case x:String =>println("String")
     | case m:Map[_,_] => m.foreach(println)
     | case _ => println("other type")

     | }}

scala> matchType(1234)
Int


scala> matchType("1234")

String

2、異常處理

scala>  try{
     | val i=1/0
     | }catch{
     | case e:ArithmeticException => println("除數不能為0")
     | case e:Exception => println(e.getMessage)
     | }finally{println("try...catch..over")}
除數不能為0

try...catch..over

#finally{.......}中的語句總會執行

3、case class

case class 不用直接new就可以直接使用,用在match語句中比較方便

class Person{}

case class Cto(naem:String,floor:String) extends extends Person{}

 case class Employee(naem:String,floor:String) extends extends Person{}

case class Other(name:String) extends Person{}

def judgeIdentify(person:Person):Unit={

person match{

case Cto(name,floor) => println("Cto")

case Employee(name,floor) =>println("Employee")

case _ => println("other")

}

}

judgeIdentify(Cto("dove","All")) 

4、高階函式

匿名函式

scala> (x:Int)=>x*x
res0: Int => Int = <function1>


scala> (x:Int,y:Int)=>x*y+x*x+y*y
res1: (Int, Int) => Int = <function2>

scala> def function=(x:Int,y:Int)=>x*y+x*x+y*y
function: (Int, Int) => Int


scala> function(1,2)

res3: Int = 7

示例:

scala> val a=Array(1,2,3,4)
a: Array[Int] = Array(1, 2, 3, 4)


scala> a.map((x:Int)=>x*2)
res8: Array[Int] = Array(2, 4, 6, 8)


scala>  a.map((x)=>x*2)
res9: Array[Int] = Array(2, 4, 6, 8)


scala>  a.map(x=>x*2)
res10: Array[Int] = Array(2, 4, 6, 8)


scala>  a.map(_*2)

res11: Array[Int] = Array(2, 4, 6, 8)

scala>  a.map(_*2).filter(_>4)
res13: Array[Int] = Array(6, 8)

scala> a.take(3)

res14: Array[Int] = Array(1, 2, 3)

scala> a.reduce((x,y)=>x+y)
res15: Int = 10


scala> a.reduce(_+_)
res16: Int = 10

#相應的reduceLeft、reduceRight、foldLeft、foldRight自己測試

scala> f.flatten
res17: List[Int] = List(1, 2, 3, 4, 2, 3, 4, 5)


scala> f.flatMap
<console>:13: error: missing argument list for method flatMap in class List
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `flatMap _` or `flatMap(_)(_)` instead of `flatMap`.
       f.flatMap
         ^


scala> f.flatMap()
<console>:13: error: not enough arguments for method flatMap: (f: List[Int] => scala.collection.GenTraversableOnce[B])(implicit bf: scala.collection.generic.CanBuildFrom[List[List[Int]],B,That])That.
Unspecified value parameter f.
       f.flatMap()
                ^


scala> f.flatMap(_.map(_*2))

res20: List[Int] = List(2, 4, 6, 8, 4, 6, 8, 10)

scala> f.map(_.map(_*2))
res23: List[List[Int]] = List(List(2, 4, 6, 8), List(4, 6, 8, 10))

5、偏函式

def sayChineseName(name:String):String=name match{

case "Akiho Yoshizawa" =>"吉老師"

case "YuiHatano" => "波老師"

case _ =>"請問您是哪個老師呀"

}

以上程式碼可用偏函式實現

def sayChineseName:PartialFunction[String,String]={

case "Akiho Yoshizawa" =>"吉老師"

case "YuiHatano" => "波老師"

case _ =>"請問您是哪個老師呀"

}

#偏函式就是一組被包含在花括號內的沒有match的一組case語句

6、String類

"my name is"+name  <=>s"my name is $name"

多行字串

scala> val b="""
     | hello
     | world
     | """.stripMargin
b: String =
"
hello
world
"

scala> println(b)

hello
world

7、隱式轉換

隱式(偷偷摸摸)的對類的方法進行增強

如果想向一個已經存在的類中在不改變該類原始碼的情況下新增一個方法,

可以採用繼承、動態代理、隱式轉換

class Man(val name:String){}

class SuperMan(val name:String){

def fly():Unit={

println(s"SuperMan $name fly...")

}

}

object obj extends App{

implict def man2superman(man:Man):SuperMan=new SuperMan(man.name)

val name=new Man("dove")

}

#此時對於傳入Man型別dove他就具有了SuperMan的fly方法,也就可以fly...了

注意:所有的隱式轉換建議封裝在一個特定的類中,使用時僅需要匯入該類即可

隱式引數自己看一看,不太重要,可以瞭解瞭解