开发者

Template pattern for strings in Scala to produce new objects

开发者 https://www.devze.com 2023-02-10 21:04 出处:网络
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?

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!


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消