Search code examples
scaladynamicreflectioncreation

Scala dynamic instantiation with default arguments


Is there a way to dynamically instantiate a Scala case class having one or more default parameters specified?

I'm looking for the dynamic (reflection-based) equivalent of this:

case class Foo( name:String, age:Int = 21 )
val z = Foo("John") 

Right now if I try this I get an exception:

val const = Class.forName("Foo").getConstructors()(0)
val args = Array("John").asInstanceOf[Array[AnyRef]]
const.newInstance(args:_*)

If I add a value for age in my parameter array, no problem.


Solution

  • Argument with default value are a compile-time thing. The compiler will feed in the default value for a call where the parameter is missing. No such thing with reflection, all the less with java reflection, which is not aware at all of default arguments.