1

Is it possible to create a class (or add attributes to a class) dynamically, e.g. load field names and types from external file in Scala?

this is follow-up on Representing nested structures in scala

2 Answers 2

2

It is possible to achieve this with macros, and there are two techniques for that with a different set of trade-offs. Refer to our joint talk with Travis Brown for more information and a link to an example implementation: https://github.com/travisbrown/type-provider-examples/blob/master/docs/scalar-2014-slides.pdf?raw=true.

Sign up to request clarification or add additional context in comments.

Comments

2

You can declare and compile a Scala class from a data structure description. It requires that you a) construct a syntactically correct class description and save it to a file (or equivalent) and then b) compile that class description to object code (i.e., a .class file). You can then load the class and use it.

This is not for the faint of heart. You need to understand the process of translation, compilation, class-loading and dynamic class binding. Even more important, you have to answer how you would actually use this in a program.

An example of dynamic class creation occurs in the Scala Play framework, where a presentation template files are translated into Scala and compiled into class files that can then be referenced from other Scala source code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.