Matthias Guenther
Matthias Guenther

Reputation: 1683

Template pattern for strings in Scala to produce new objects

Is it possible in Scala to create a string, which gets code of a class or method declaration which will be then executed and after that new objects will be created?

Here is an example in ruby code:

"class #{name}; def #{method_name}; \"#{block.call}\"; end; end"

Do you know any examples or links for my approach?

Thanks for your help!

Upvotes: 0

Views: 159

Answers (3)

Landei
Landei

Reputation: 54584

Sure, you can get this somehow working by calling the compiler with a given String, and then you probably need a custom classloader. However Scala is a static language, so it will never be as convenient and elegant as in Ruby or other dynamic languages.

[Edit]

I never tried it, but I found this link: http://scala-programming-language.1934581.n4.nabble.com/Compiling-a-Scala-Snippet-at-run-time-td2000704.html

Upvotes: 4

shellholic
shellholic

Reputation: 6114

Design patterns are made to circumvent common problem with a common solution. Here you are trying to use a foreign design pattern and try to translate it word by word. Be careful, particularly with dynamic language patterns.

Specifically for your question, the template pattern in Java is commonly a language construct named abstract classes. In Scala you can also make abstract classes and traits.

Another trap, the singleton design pattern is a language construct in Scala.

Upvotes: 1

Sam Stainsby
Sam Stainsby

Reputation: 1608

I'm not sure what higher-level problem you are trying to solve, but I imagine the Scala REPL must do this all the time when you enter lines of code interactively. I seem to recall developers have successfully integrated this with applications that need to generate code dynamically.

However, as Rex points out, there are probably better solutions to your underlying problem than resorting to sloppy, unsafe mechanisms such as this.

Upvotes: 0

Related Questions