I was making good progress with Scala's pattern matching (amazing btw) until I tried to make a dynamic function to match "Instance of" and in the future as part of an object maybe save that [type] for later. Now I understand how to use pattern class matching
case X:Int => ....
but why does this (below) seem to work for anything passed to it?? Further more I can't really seem to work with [TYPE] , is it an object? I can't print it or val = , etc.. I thought about trying to work with the java.Class associated but that doesn't seem correct. Any advise is appreciated, thank you!
class Parent
class Child extends Parent
object TestTypes {
def testRelate[TYPE](o:Any) = {
o match {
case o:TYPE => println(" o is a matching type")
case _ => println(" o fails")
}
// val save = [TYPE] .. why can't I do this?
}
def main(args: Array[String]): Unit = {
val p = new Parent
val c = new Child
testRelate[Int](c) // why does this Match???
testRelate[Parent](c) //
}
}
--- Update so just to clarify (and thank you for the answers) but how then can someone accomplish pattern matching of classtype dynamically during runtime? It seems scala has a static type matching (that beings to breakdown in the example above), but is instanceOf( ) my choice of dynamic checking?