How to map a pattern to class [X] for different X?

I want to check the type of method parameters, but I do not know how to do this. See my code:

class X { def x(a: Int, b: String) {} } val methods = classOf[X].getDeclaredMethods methods map { m => m.getParameterTypes.toList map { t => println(t.getName) // I don't know how to write the following if ( the type of t is Int) { do something} else if( the type of t is String ) { do something} else { } } } 

Pay attention to the comment in the code. I do not know how to check types in a scala way.

I tried:

 t match { case _:String => println("### is a string") case _:Int => println("### is an int") case _ => println("### ?") } 

But it cannot be compiled.

I can use the java path to check:

 if (t.isAssignableFrom(classOf[String])) // do something else if(t.isAssignableFrom(classOf[Int])) // do something else {} 

It seems we should use it in scala, right?


UPDATE:

If I want to use match , I have to write like this:

 t match { case i if i.isAssignableFrom(classOf[Int]) => println("### is an Int") case s if s.isAssignableFrom(classOf[String]) => println("### is a String") case _ => println("###?") } 

Is this the best answer?

+8
types scala
source share
2 answers

I could make it work with t as a type, defining cases as constants. It does not compile with class literature as an expression of chance. Try:

 val S = classOf[String] val I = classOf[Int] t match { case S => println("### is a string") case I => println("### is an int") case _ => println("### ?") } 
+10
source share

You can use ClassManifest.fromClass to correctly handle forcing primitives on AnyVals, and any other such problems that you might encounter in a box with non-free types when inflating with reflection.

Like this:

 import reflect.ClassManifest class Wibble { def method(a:Int, b: String) = () } for(method <- classOf[Wibble].getDeclaredMethods; paramType <- method.getParameterTypes) { ClassManifest.fromClass(paramType) match { case m if m <:< ClassManifest.Int => println("Interiffic") case m if m <:< ClassManifest.Float => println("Floaty, like butterflies") case m if m <:< ClassManifest.Double => println("Or Quits...") //todo: all the other AnyVal types... case m if m <:< classManifest[String] => println("bleeding edge physics, yeah baby!") //...and a default condition } } 
+7
source share

All Articles