开发者

How to get an object's specific type and cast the object to it in Scala?

开发者 https://www.devze.com 2023-01-19 06:14 出处:网络
For example GeneralType is a class or a trait extended by many more specific types, including, to say,SpecificType.

For example

GeneralType is a class or a trait extended by many more specific types, including, to say, SpecificType.

A function takes an argument of type GeneralType, and then whant's no know if开发者_如何学C the actual argument passed is a SpecificType instance and act accordingly (use its special fields/methods) if it is.

How to code this in Scala 2.8?


In a word... "Pattern Matching":

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)
}


Put this script in a file:

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)

Run the script:

scala match_type.scala 
GeneralT
SpecificT


http://programming-scala.labs.oreilly.com/ch03.html#MatchingOnType ?

0

精彩评论

暂无评论...
验证码 换一张
取 消