user2607928
user2607928

Reputation: 39

Initializing the factory at compile time

I have a factory that should return an implementation depending on the name.

    val moduleMap = Map(Modules.moduleName -> new ModuleImpl)
    def getModule(moduleName: String): Module =
        moduleMap.get(moduleName) match {
          case Some(m) => m
          case _ =>
            throw new ModuleNotFoundException(
              s"$moduleName - Module could not be found.")
        }

In order for each call to the "getModule" method not to create an instance, there is a map in which all the modules must be initialized in bootstrap class. I would like to get rid of the need to do this manually(also all classes have a distinctive feature).

List of options that came to my mind:

Can we move initialization process to compile time?

I know that compiler can optimize and replace code, next fragment before compilation

val a = 5 + 5

after compilation compiler change that piece to 10, can we use some directives or another tools to evaluate and execute some code at compile time and use only final value?

Upvotes: 1

Views: 139

Answers (1)

Evgeny
Evgeny

Reputation: 1770

Do you use any framework or you write your own? I answered similar question about Guice here. You can use it without Guice as well: instead of Module you will have your Factory, which you need to initialize from somewhere, and during initialization, you will fill your map using reflection

In general I think it is the easiest approach. Alternatively, you can write macros, which just replaces part of reflective initialization, but not sure that it will give you some profit (if I understand your question right, this initialization will happen just once at startup).

I do not see how scalameta can help you? Probably, only in case if all your implementations are in source tree available to you, so you can analyze it and generate initialization (similar to macros)? Probably, this would add such plus as easier search for implementation, but will add minus: will work only on implementations in your sources.

Your example of compile-time optimization is not applicable. In your example, you talk about compile-time constant (even with arithmetic it could be a problem, see this comment), but in your question you need specific run-time behavior. So compile time could be only code generation from macros or based on scalameta from my point of view.

Upvotes: 0

Related Questions