Scala 中字符串的模板模式用于生成新对象
Scala 中是否可以创建一个字符串,该字符串获取类或方法声明的代码,然后执行该代码,然后创建新对象?
这是 ruby 代码中的一个示例:
"class #{name}; def #{method_name}; \"#{block.call}\"; end; end"
您知道我的方法有任何示例或链接吗?
感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,您可以通过使用给定的字符串调用编译器来以某种方式使其工作,然后您可能需要一个自定义类加载器。然而Scala是一种静态语言,因此它永远不会像Ruby或其他动态语言那样方便和优雅。
[编辑]
我从未尝试过,但我找到了这个链接: http://scala-programming-language.1934581.n4.nabble.com/Compiling-a-Scala-Snippet-at-run-time-td2000704.html
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
设计模式旨在通过通用解决方案来规避常见问题。在这里,你尝试使用一种外国设计模式,并尝试逐字翻译它。要小心,尤其是动态语言模式。
针对您的问题,Java 中的模板模式通常是一种名为抽象类的语言构造。在 Scala 中,您还可以创建
抽象类
和trait
。另一个陷阱,单例设计模式是 Scala 中的一种语言构造。
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 class
es. In Scala you can also makeabstract class
es andtrait
s.Another trap, the singleton design pattern is a language construct in Scala.
我不确定您想要解决什么更高级别的问题,但我想当您交互输入代码行时,Scala REPL 必须始终执行此操作。我似乎记得开发人员已经成功地将其与需要动态生成代码的应用程序集成。
然而,正如雷克斯指出的那样,对于你的根本问题,可能有比诉诸诸如此类的草率、不安全的机制更好的解决方案。
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.