Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Scala Class as parameter?

Tags:

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.

like image 801
GroomedGorilla Avatar asked Jan 23 '15 15:01

GroomedGorilla


People also ask

How do you call a class 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.

Can Scala object take parameters?

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.

What is the meaning of => in Scala?

=> 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 .


1 Answers

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 
like image 189
Herrington Darkholme Avatar answered Sep 28 '22 01:09

Herrington Darkholme