LaloInDublin
LaloInDublin

Reputation: 5449

Pattern matching Type as a parameter for functions, methods, etc

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?

Upvotes: 1

Views: 445

Answers (2)

Connor Doyle
Connor Doyle

Reputation: 1912

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

Upvotes: 1

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297275

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.

Upvotes: 4

Related Questions