2

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?

Ivan
  • 63,011
  • 101
  • 250
  • 382
  • Related: Manifests and Type classes emulated with implicits http://stackoverflow.com/q/3307427/203968 – oluies Oct 11 '10 at 08:50

3 Answers3

3

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
  • 49,540
  • 9
  • 105
  • 155
2

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
  • 6,249
  • 2
  • 20
  • 31