Technically speaking it's possible using reflection. You could for example catch runtime class of type T using ClassTag
then find proper constructor and create instance:
def createObject[T](fieldValues: Seq[Any])(implicit ct: ClassTag[T]): Option[T] = {
//we lookup for matching constructor using arguments count, you might also consider checking types
ct.runtimeClass.getConstructors.find(_.getParameterCount == fieldValues.size)
.flatMap {constructor =>
Try(constructor.newInstance(fieldValues: _*).asInstanceOf[T]).toOption
}
}
createObject[Person](Seq("Bob", 20)) //Some(Person("Bob", 20))
createObject[Person](Seq(20, 10)) //None
In case there's no constructor matching parameters, that function fails returning None
.
It should work, but it'd be best if you can avoid this approach because you lose all type safety.