例如
GeneralType是由更多特定类型扩展的类或特征,包括,例如,SpecificType。
一个函数接受GeneralType类型的参数,然后whant不知道传递的实际参数是否是一个SpecificType实例并且相应地采取行动(使用它的特殊字段/方法),如果它是。
如何在Scala 2.8中编写代码?
答案 0 :(得分: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)
}
答案 1 :(得分: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
答案 2 :(得分:0)