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.
Defining a classWe call the class like a function, as User() , to create an instance of the class. It is also possible to explicitly use the new keyword, as new User() , although that is usually left out. User has a default constructor which takes no arguments because no constructor was defined.
Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
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 type Class[_]
as you have done.
def sample(c: Class[_]) = println("Get a class") sample(classOf[Int])
However, if you want to check whether an object is of certain type, I recommend you to use =:=
, in combination with default parameter
def checkType[T](obj: T)(implict ev: T =:= Int = null) = if (ev == null) "get other" else "get int" checkType(123) // get int checkType("123") // get other
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With