總結scala(五)
十四、模式匹配(match:關鍵字)
1、偏函數
[String,Int]:函數的參數是String類型,返回的值是int類型
def fun1:PartialFunction[String,Int] = {
case "a" => 1
case "b" => 2
case "c" => 3
case _ => 0
}
2、匹配字符串
def fun2(num:String):Int = num match {
case "one" => 1
case "two" => 2
case _ => -1
}
3、匹配類型
def fun3() = {
val arr = Array("hello world",2,3.14)
//隨機產生一個角標,3不會獲取到
val a = arr(Random.nextInt(3))
a match {
case x:Int => println(x)
case y:Double =>println(y)
case z:String => println(z)
case _ =>println("not match")
}
}
4、匹配數組
def fun4() = {
val arr = Array(1,2,3,4,5)
arr match{
case Array(1,x,y) => println(x + y) //匹配以一打頭的數組,只有三個元素的數組
case Array(0) => println("only 0") //匹配只有一個元素的數組,並且這個元素是0
case Array(1,_*)=>println("1....") //匹配的是以一打頭,任意長度的數組
case _ =>println("something else")
}
}
5、匹配list序列
def fun5() ={
val lst = List(1,0)
lst match {
case 5 :: Nil => println("only 5") //匹配只有一個元素,這個元素是5的序列
case x :: y :: Nil => println(s"x:$x y:$y") //匹配只有兩個元素的序列
case x :: tail => println("0...") //以任意元素開頭,後面有多個元素的序列
case _ => println("something else")
}
}
6、匹配元組
def fun6() = {
val tup = (1,"true",3)
tup match {
case (x,y,3.14) => println(x+y)
case (2,x,y) => println(x+y)
case (x,"true",y)=>println(x+y)
case _ => println("unknown")
}
}
7、類的匹配
val d:Animal = new Dog
d match {
case e:Animal => println("Animal")
case e:Dog => println("Dog")
case e:Cat => println("Cat")
case _ => println("unknown")
}
十五、trait(接口)
1、類多重繼承Trait
scala不支持對類進行多繼承,但是支持多重繼承trait,使用with關鍵字即可
類繼承trait後,必須實現其中的抽象方法,實現時不需要使用override關鍵字,也可以調用trait裏面實現的方法
但是這種獲取屬性的方式與繼承class是不同的:如果是繼承class獲取的屬性,實際是定義在父類中的,而繼承trait獲取的屬性,就直接被添加到了類中
代碼:class Student extends Humen with Trait01 with Trait02
一個類繼承了trait,可以實現trait中具體方法中的抽象方法。
2、對象混入某個trait
在創建類的對象時,指定該對象混入某個trait,這樣,就只有這個對象混入該trait的方法,而類的其他對象則沒有
代碼:val childer1 = new Childer("李晟男",23) with Trait03
3、trait繼承trait
(1)、在scala中,是可以覆蓋父trait的抽象方法的
但是覆蓋時,如果使用了super.方法的代碼,則無法通過編譯,因為super.方法就會去掉用父trait的抽象方法
此時子trait的該方法還是會被認為是抽象的,所以想通過編譯,子trait中覆蓋父trait 的方法前加上abstract
(2)、調用鏈條
Scala中支持讓類繼承多個trait後,依次調用多個trait中的同一個方法,只要讓多個trait的同一個方法中,
在最後都執行super.方法即可。
類中調用多個trait中都有的這個方法時,首先會從最右邊的trait的方法開始執行,然後依次往左執行,
形成一個調用鏈條
這種特性非常強大,其實就相當於設計模式中的責任鏈模式的一種具體實現依賴
5、trait的構造機制
在scala中,trait也是有構造代碼的,也就是trait中的,不包含在任何方法中的代碼
而繼承了trait的類的構造機制如下:
1、父類的構造函數執行;
2、trait的構造代碼執行,多個trait從左到右依次執行;
3、構造trait時會先構造父trait,如果多個trait繼承同一個父trait,則父trait只會構造一次
4、所有trait構造完畢之後,子類的構造函數執行
6、trait繼承類
在scala中,trait也可以繼承自class,此時這個class就會成為所有繼承該trait的類的父類
總結scala(五)