伴生对象中的 Scala 受保护构造函数和生成器
我有一些带有受保护构造函数的类,并且工厂方法位于抽象超类的伴随对象内。从 Scala 2.9.0.RC4 开始,它不再编译。我通过对构造函数进行包保护来“解决”了这个问题。但我不希望同一包内的其他类能够调用构造函数。
那我该怎么办?
sealed abstract class A
object A {
//the factory method, returning either a B or C
def apply(): A
}
class B protected (...) extends A
class C protected (...) extends A
I have some classes with a protected constructor and the factory method is inside the companion object of an abstract super class. As of Scala 2.9.0.RC4 this doesn't compile anymore. I have "fixed" the issue by making the constructors package protected. But I don't want other classes even inside the same package to be able to call the constructors.
So what should I?
sealed abstract class A
object A {
//the factory method, returning either a B or C
def apply(): A
}
class B protected (...) extends A
class C protected (...) extends A
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将它们设为对象的私有内部类。
You could make them private inner classes of the object.
由于您需要可访问的类以进行模式匹配,因此我建议为它们创建一个新的子包,并将构造函数设为该包的私有。现在只需更改客户端代码中的导入语句。
Since you need the classes accessible for pattern matching, I would suggest creating a new subpackage for them and making the constructor private to that package. Now only the import statements in your client code need to be changed.
另一种选择是为 A 的每个实现创建伴随对象,并将构造委托给该对象中的工厂方法:
Another option is to create companion objects for each implementation of A and delegate construction to a factory method in this object: