2010-10-11 43 views
2

例如如何獲取對象的特定類型並將對象轉換爲Scala中的對象?

GeneralType是一個類或一個特徵擴展了許多更具體的類型,包括說,SpecificType。

一個函數具有類型一般型的參數,然後whant沒有知道,如果傳遞的實際參數是一個SpecificType實例,並採取相應的行動(利用其特殊的字段/方法),如果它是。

如何在斯卡拉2.8的代碼呢?

+0

相關:艙單及使用implicits模擬類型類http://stackoverflow.com/q/3307427/203968 – oluies 2010-10-11 08:50:24

回答

3

一句話...... 「模式匹配」:

def method(v : Vehicle) = v match { 
    case l : Lorry  => l.deliverGoods() 
    case c : Car  => c.openSunRoof() 
    case m : Motorbike => m.overtakeTrafficJam() 
    case b : Bike  => b.ringBell() 
    case _ => error("don't know what to do with this type of vehicle: " + v) 
} 
2

將這個腳本文件:

trait GeneralType 

class SpecificType extends GeneralType 

def foo(gt: GeneralType) { 
    gt match { 
    case s: SpecificType => println("SpecificT") 
    case g: GeneralType => println("GeneralT") 
    } 
} 

val bar = new AnyRef with GeneralType 
val baz = new SpecificType() 

foo(bar) 
foo(baz) 

運行腳本:

scala match_type.scala 
GeneralT 
SpecificT 
相關問題