I'm looking to pass a Class as a parameter to a Scala function like so:
def sampleFunc (c : Class) : List[Any]
(Side question: should the type in the parameter be Class or Class[_]?)
The reason I'm passing a Class type is to check whether an object belongs to a particular type or not. At the moment, as a workaround, I'm passing a sample object to the method and comparing the two object's .getClass result. I hardly think this is ideal though and I'm sure there's a clearly defined way of passing Types in Scala.
In Scala, if you need to deal with classes, there is probably a different way to approach the problem.
So I'm not claiming to resolve the title of the question, but the specific need that you post. To check if a specific object is of a specific type, the typical approach in Scala is the use of pattern matching. Unless I'm missing something, this should work
See http://docs.scala-lang.org/tutorials/tour/pattern-matching.html
Well, to your original question: Yes, you can pass Scala Class as an argument. As
Class
is a type constructor, it needs a concrete type to make a type to be used in argument. You can use the wildcard existential typeClass[_]
as you have done.However, if you want to check whether an object is of certain type, I recommend you to use
=:=
, in combination with default parameterYes. In general case it's
ClassTag
/TypeTag
- see Mirrors and ReflectionIf you really need only to check compile-time (formal) type equality
If you really need to check only type of object: