Scala:我可以使用工厂方法重现匿名类的创建吗?
据我了解,如果我使用 new 关键字创建一个类并在类名后面加上构造函数,Scala 就会创建一个匿名类:
class MyClass {
def doStuff() {
// ...
}
}
val mc = new MyClass {
doStuff()
}
好处是构造函数中的所有代码都在新对象的范围。
有没有办法可以重现这种语法,其中类是由工厂方法而不是 new 关键字创建的?即让下面的代码工作:
val mf = new MyFactory
val mc = mf.MyClass {
doStuff()
}
我找不到一种方法来做到这一点,但 Scala 的功能非常丰富,这可能非常简单!
使用下面 @Ricky 建议的 import
我可以得到:(
val mf = MyFactory;
val mc = mf.MyClass
{
import mc._
doStuff()
}
需要块之前的空行)但该代码块不是构造函数。
As far as I understand it, Scala creates an anonymous class if I create a class using the new
keyword and follow the class name with a constructor:
class MyClass {
def doStuff() {
// ...
}
}
val mc = new MyClass {
doStuff()
}
The nice thing being that all the code in the constructor is in the scope of the new object.
Is there a way I can reproduce this syntax where the class is created by a factory method rather than the new
keyword? i.e. make the following code work:
val mf = new MyFactory
val mc = mf.MyClass {
doStuff()
}
I can't find a way to do it but Scala has so much to it that this might be pretty easy!
Using an import
as suggested by @Ricky below I can get:
val mf = MyFactory;
val mc = mf.MyClass
{
import mc._
doStuff()
}
(Where the blank line before the block is needed) but that code block is not a constructor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以这样做,但仍然必须保留 new 关键字,并将嵌套类创建为路径相关类型:
You can do this, but you still have to keep the
new
keyword, and create the nested class as a path-dependent type:我认为这是不可能的。然而,一种常见的模式是向工厂方法添加一个参数,该方法采用修改创建的对象的函数:
然后您可以使用与示例接近的语法创建和修改实例:
I don't think it's possible. However, a common pattern is to add a parameter to factory methods which takes a function modifying the created object:
You can then create and modify instance with a syntax close to your example:
听起来你只是想融入一种特质。 而不是调用 myFactoryMethod(classOf[Foo]] :
理想情况下,您可以编写
以下内容, 稳定标识符:
It sounds like you're just looking to mix in a trait. Instead of calling myFactoryMethod(classOf[Foo]] which ideally would do (if Scala permitted it):
you can instead write
However, if you are just looking to get the members of the new object accessible without qualification, remember you can import from any stable identifier: