Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching without case classes

Is it possible, through pattern matching, to detect the subtype of a class that is not a case class?

I need to use existing Java classes, so I can't declare my own case classes.

like image 361
loopbackbee Avatar asked Nov 15 '13 14:11

loopbackbee


1 Answers

Yep! You can pattern match on type, so if you have different cases for different subtypes, you can get the behavior you're looking for:

trait A
class B extends A
class C extends A

def f(a: A) = a match {
  case b: B => "a B!"
  case c: C => "a C!" 
}

f(new B)  // a B!
f(new C)  // a C!
like image 62
dhg Avatar answered Oct 17 '22 06:10

dhg