Created
December 11, 2010 17:46
-
-
Save mkmik/737496 to your computer and use it in GitHub Desktop.
demonstrate addition of methods to existing classes, and typesafe dynamic pattern matching on baseclass references
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Base { | |
def doit = println ("base") | |
} | |
class Sub1 extends Base { | |
override def doit = println ("sub1") | |
def onething = println("specific to sub1") | |
} | |
class Sub2 extends Base { | |
override def doit = println ("sub2") | |
def otherthing = println("specific to sub2") | |
} | |
class Sub3 extends Base { | |
override def doit = println ("sub3") | |
} | |
/// extensions | |
// this are just helper methods for pattern-match/destructuring | |
object Sub1 { | |
def unapply(s : Sub1) = Some("ciao from s1") | |
} | |
object Sub2 { | |
def unapply(s : Sub2) = Some("ciao from s2") | |
} | |
// this one demonstrates a pattern match on subclasses of Base and destructuring assignment | |
case class BaseStuff(val thing: Base) { | |
def act = { | |
println ("base stuff .... ") | |
thing match { | |
case sub1 : Sub1 => | |
// the following 3 lines are equivalent | |
// sub1 match {case Sub1(message) => println("acting on a sub1 " + message)} | |
// val message = sub1 match { case Sub1(message) => message} | |
val Sub1(message) = sub1 | |
println("acting on a sub1 " + message) | |
sub1.onething | |
case Sub2(message) => | |
println("acting on a sub2 " + message) | |
// By using destructuring/pattern-match in the case pattern, we don't have access to the value casted with type Sub2 | |
// sub2.otherthing | |
// but we can cast it | |
(thing.asInstanceOf[Sub2]).otherthing | |
case _ => | |
println("unhandled case....") | |
} | |
} | |
} | |
// this one adds the method "act" to instances of "Base" | |
implicit def base2basestuff(x: Base) = new BaseStuff(x) | |
val ss = List(new Sub1, new Sub2, new Sub3) | |
println("-- testing") | |
ss.foreach(s => s.act) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment