Scala case class creation run time or load case calss from external file

I need to create case class run time as there can be a list of parameter changes each time, I run the program.Please can you provide example for the same.

Can we load case classes at run time in the scala application, if yes please provide the simple example.

Thank you in advance :slight_smile:


How will you write code to do something useful with that case class if you only know at runtime which fields it will have?


For the record, your app could write the necessary source code, send it to
the compiler, load it using a custom classloader, and then create instances.

But why do you need to do this?

As Jasper implies, your static code has no way of referring to a
dynamically created type and its members, except where it extends a
previously known static type.

A straight-forward technique would be to have a trait A in your code and
then you dynamically create a new class B that extends A, then create an
instance of B (which initially will have an AnyRef reference) and cast it
to A and use members of A.

But do you really need this or could you just use a List[Any] or

Best, Oliver

Hi Curoli,

Thank you for your insight on this.
for instance : case class Person(name , String , age:Int, gender :String), in this case I know there are fixed number of parameters , but to scale it up,would like to read all parameters from file or any other source and pass to case class and the same case class want to use it spark to bind the schema with data.
Please share if any example.

Thank you in advance :slight_smile:

As others have pointed out, there are several ways to dynamically represent data in scala

  • Use Map[String, Any] or Map[String, A] to record parameters.
  • Use a type Option[A] for an optional parameter.
  • Use more than one case class, with a common sealed trait to handle different kinds of data.
  • Use an AST for Json, say that from circe to store data.
  • Create your own AST similar to JSON.

I assume you have some reason to specifically use case classes. It would help if you spell out this reason.


Personally, Iā€™m a fan of type Anything = Map[String, Anything]. With a little indirection so it compiles.