I have many classes of a common base trait. I have a function that needs to create a new instance of a instance of one of these classes, but which one is only known at runtime.
Is it possible to pass this class as a parameter and create an instance at runtime in Scala?
I'm not even sure that the answer would be the best approach but currently it's the only thing I can think of.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor.
To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.
Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.
Constructor(s) of a class must have the same name as the class name in which it resides. A constructor in Java can not be abstract, final, static, or Synchronized. Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.
You could pass the value thus:
myFunc(classOf[myObj])
to the method with signature
def myFunc(clazz : AnyRef)={ ...
but this smells bad. You're either looking at implementing a factory pattern, or better still you could use polymorphism and simply do:
myObj.myFunc
since your functionality is predicated on what class is involved.
Same as in Java:
classOf[MyClass].newInstance // calls the constructor without parameters
classOf[MyClass].getConstructor(/* parameter types */).newInstance(/* parameters */)
See Javadoc for Class.
This will work in any Scala version. Scala 2.10 has new reflection libraries, which are aware of Scala concepts.
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