1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
LaloInDublin
  • 5,379
  • 4
  • 22
  • 26
  • 3
    Tip: when the compiler tells you that something isn't right, pay attention to it. – Daniel C. Sobral Jul 05 '12 at 00:18
  • 1
    See the edit part of [this post](http://stackoverflow.com/questions/11310547/how-to-distinguish-between-objects-with-different-abstract-type-fields/11311312#11311312). (This is the third time I am posting this this week.) – missingfaktor Jul 05 '12 at 04:59

2 Answers2

4

Type parameters are erased at run time, so TYPE is effectively equivalent to Object, which means anything.

Also type parameters are types, not values, so you can't assign it to a variable. At most, you could do this:

type save = TYPE

However, that is erased too, so it isn't saving anything.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • Thank you, would you happen to know how this might working using java.class .. or does Scala have it's own "class" object type? – LaloInDublin Jul 05 '12 at 03:19
  • @LaloInDublin This happens at compile time, so class files aren't much of a concern. However, Scala stores type information as constants on class files, to allow for separate compilation. You can look at it with `javap`, though it's binary-encoded and, thus, illegible. – Daniel C. Sobral Jul 06 '12 at 22:49
1

For more powerful runtime type checking you may want to look at scala.reflect.Manifest[T]. It wraps a java.lang.Class[T] and adds some nice variance checking operators.

Here is a usage example: The EnMAS POMDP State Class

Connor Doyle
  • 1,812
  • 14
  • 22