模式匹配
模式匹配
樣例類
封閉類
偏函數react
it-auto; text-indent: 0px; text-transf模式匹配
模式匹配是數據結構上的概念
val hi=Array("hi","hello","world")
hi match{
case Array(「hi」, _*) => println(「Ok」)
case Array("hi","world",_) => println("Wrong")
case _ => println(「None") }
數據結構包括各類集合,類,函數等
通配符 「 _」表示任意,「 _*」則表示任意長度,web
模式匹配
類型匹配
def getType(a:Any){
a match{
case _ :Array[Char] => println("Array[Char]")
case _ :Int => println("Int")
case _ :Char => println("Char")
case _ => println(「Error")
} }
注意:泛型的類型匹配要注意如List[String]、 Map[Char,Int]等不會成功匹配,如
List[Int]等亦可匹配,於是每每使用通配符List[ _ ]進行匹配,但Array[Int]是可行的數據結構
m: none; white-space: normal; widows: 樣例類
abstract class Expr
case class Number( n :Int) extends Expr
case class Sum(e1 : Expr , e2 : Expr) extends Expr
case object Mul(e1 : Expr , e2 : Expr) extends Expr .
def getType(a:Expr):String =
a match{
case Number(n) => 「 Number「
case Sum(m,n) => 「Sum「
case _ => 「Else"
}ide
樣例類
abstract class Expr{
def getType : String = this match {
case Number(n) => 「Number」
case Sum(e1 , e2) => 「Sum」 } }
val hi=new Number(4)
val hello=new Sum(3,7)
hi.getType =「Number」 hello.getType =「 Sum」
樣例類默認生成toString、 equals、 hashCode跟copy方法函數
封閉類
模式匹配完成後須要確保全部狀況皆被考慮
Scala編譯器會檢測match表達式所遺漏的模式組合
使樣本類的超類被封閉(sealed),封閉類除類定義文件外不能添加子類
sealed abstract class Expr
case class Number( n :Int) extends Expr
case class Sum(e1 : Expr , e2 : Expr) extends Expr
case class Mul(e1 : Expr , e2 : Expr) extends Exprthis
封閉類
如何定義存在可能樣本遺漏的模式匹配
def getType(a:Expr):String =
a match{
case Number(n) => 「Number「
case Sum(m,n) => 「 Sum「}
warning : match is not exhaustive
case _ =>
添加註解
def getType(a:Expr):String = (a: @unchecked ) match {...}spa
normal; line-height: normal; orphans: 偏函數
限定輸入參數的值的函數
把函數應用到其不支持的值時,產生運行異常
PartialFunction[A,B],Scala包中給出的部分函數類型
val getNum:PartialFunction[Int,String] ={
case 1 => 「one」
case 2 => 「two」}
getNum.isDefinedAt(1) = true
getNum.isDefinedAt(3) = false
PartialFunction能夠使用orElse組成新的函數
val part= getNum orElse getSize orElse getLength.net
g: 0px; -webkit-text-size-adjust: auto偏函數
把參數模式匹配
react{
case (name:String , actor:Actor) =>{
actor ! getip(name)
act( ) }
case msg =>{
println(「Unhandled message:」+msg)
act( ) } }rest
: auto; -webkit-text-stroke-width: 0px類型參數
泛型
類型變量界限
型變(協變與逆變)orm
-space: normal; widows: 2; word-spacin泛型
abstract class IntStack{
def push(x:Int):IntStack = new IntNonEmptyStack(x,this)
def isEmpty:Boolean
def top:Int
def pop:IntStack}
class IntEmptyStack extends IntStack{
def isEmpty=true
def top=error(「EmptyStack.top」)
def pop=error(「 EmptyStack.pop」) }
class IntNonEmptyStack(elem:Int,rest:IntStack) extends IntStack{
def isEmpty=false
def top=elem
def pop=rest }
-spacing: normal; line-height: normal;泛型
類、特質、函數、方法可帶有類型參數
def getType(a:Any) //a是Any類型
def getType[T](a:T) //a是泛型,getType是泛型函數
class Pair[T,S](val first:T,val second:S) //泛型類
trait Pair[T] //泛型特質
當類型被指定的時候構成具體的類、函數等
val getInt = getType[Int] _
支持類型推斷
val p1=new Pair[25,25.0] //生成Pair[Int,Double]類
val p2=new Pair[25.0,25]
-space: normal; widows: 2; word-spacin泛型
abstract class Stack[T]{
def push(x:T):Stack[T] = new NonEmptyStack[T](x,this)
def isEmpty:Boolean
def top:T
def pop:Stack[T]}
class EmptyStack[T] extends Stack[T]{
def isEmpty=true
def top=error(「EmptyStack.top」)
def pop=error(「 EmptyStack.pop」) }
class NonEmptyStack[T](elem:T,rest:Stack[T]) extends Stack[T]{
def isEmpty=false
def top=elem
def pop=rest }
泛型
val m=new IntEmptyStack
val m=new EmptyStack[Int]
val n=new EmptyStack[Array]
val q=m.push(1).push(2)
val p=n.push(Array(5,7,9)).push(Array('5','7','9'))
style=" font-style: normal; font-vari類型參數界限
對於泛型結構,類型參數界限能限制應用在該泛型上的類型
Ordered[T]:Scala標準庫中提供的一個特質,用以表示可比較的類型
abstract class Stack[ T <: Ordered[T] ]
class EmptyStack[ T <: Ordered[T] ] extends Stack[T]
class NonEmptyStack[ T <: Ordered[T] ](elem:T,rest:Stack[T]) extends Stack[T]
能夠經過自行構建的類混入Ordered特質使之符合參數界限(能比較)
類型參數上界實則經過限制類型必須擁有某些特質
T <: Compatable[T]
T <: Integral[T]
: normal; line-height: normal; orphans類型參數界限
abstract class Stack[ T <: Ordered[T] ]
class EmptyStack[ T <: Ordered[T] ] extends Stack[T]
class NonEmptyStack[ T <: Ordered[T] ](elem:T,rest:Stack[T]) extends Stack[T]
val m=EmptyStack[Int]
Int不是Ordered[Int]的子類,但RichInt是
視界限定
T <% Ordered[T] // T 能夠被隱式轉換爲Ordered[T]
相似的,便有類型參數下界
R >: S //S是R的子類,R是S的超類
ont-style: normal; font-variant: norma類型參數界限
上下文界定
T : M //M[T]是在源碼中定義的另外一個泛型類
多重界定
T >: lower <:upper //同時有上下界,但不能同時有多個上界或下界
T <: Ordered[T] with Cloneable //能要求同時混入多個特質
T <% Ordered[T] <% String //能同時多個視圖限定
T : Ordering : Manifest //能同時多個上下文界定
類型約束
T =:= U T <:< U T <%< U
使用類型約束需添加(implicit ev: T <:< U)
ormal; font-variant: normal; font-weig型變(協變與逆變)
class School
class Student extends School
Stack[School]與Stack[Student]沒有任何關係,是兩個獨立的類
class Stack[+T] +號意味着Stack與T是協變的,Stack與T朝着一樣的方向型變
Stack[Student] extends Stack[School]
class Stack[-T] -號意味着Stack與T是逆變的,Stack與T朝着相反的方向型變
Stack[School] extends Stack[Student]
注意:泛型的類型聲明中能夠同時使用協變和逆變
t-indent: 0px; text-transform: none; w型變(協變與逆變)
trait Function1[-T,+R] extends AnyRef
class Animal(val sound =「rustle」)
class Bird extends Animal(override val sound=「call」)
class Chicken extends Bird(override val sound=「cluck」)
val getTweet : (Bird =>String) =( (a:Animal) => a.sound )
getTweet : Bird =>String = <fouction1>
//輸入參數是逆變的,只能是Bird的超類
val hatch : ( ( )=>Bird ) =( ( )=>new Chicken )
hatch : ( ) => Bird =<function0>
//輸出值是協變的,能夠是Bird的子類