views:

82

answers:

3

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 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?

+2  A: 

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
olle kullberg
+3  A: 

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