Scala 额外的无参数构造函数加上默认构造函数参数
我在构造函数上使用 Scala 2.8 默认参数,并且出于 Java 兼容性原因,我想要一个使用默认参数的无参数构造函数。
由于非常合理的原因,这不起作用:
class MyClass(field1: String = "foo", field2: String = "bar") {
def this() = {
this() // <-- Does not compile, but how do I not duplicate the defaults?
}
}
我想知道是否缺少任何东西。有不需要复制参数默认值的想法吗?
谢谢!
I am using the Scala 2.8 default parameters on a constructor, and for Java compatibility reasons, I wanted a no-arg constructor that uses the default parameters.
This doesn't work for very sensible reasons:
class MyClass(field1: String = "foo", field2: String = "bar") {
def this() = {
this() // <-- Does not compile, but how do I not duplicate the defaults?
}
}
I am wondering if there is anything that I am missing. Any thoughts that don't require duplicating the parameter defaults?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我真的不推荐它,但您可以通过向构造函数添加另一个参数来实现:
Unit
是一个不错的选择,因为无论如何您只能将一个东西传递给它,因此显式传递默认值不允许任何错误的可能性,但它允许您调用正确的构造函数。如果您愿意仅复制一个默认值,则可以使用相同的策略,只不过覆盖所选的默认值而不是添加单位参数。
I wouldn't really recommend it, but you can do it by adding another parameter to your constructor:
Unit
is a good choice because you can only pass one thing into it anyway, so explicitly passing the default value doesn't allow any possibility of error, and yet it lets you call the correct constructor.If you're willing to replicate just one of the defaults, you can use the same strategy except override that one chosen default instead of adding the unit parameter.
作为好奇的变通黑客,我的意思是黑客:您可以使用默认参数的内部表示:
请注意,需要在 this(MyClass.init$default$1) 中包含 MyClass 。部分解释是默认参数保存在伴生对象中。
As curious work-around hack, and I do mean hack: you can use the internal representation of default arguments:
Notice that it's needed to include MyClass in this(MyClass.init$default$1). A partial explanation is that the default arguments are kept in companion objects.
您可以考虑使用工厂方法:
然后从 Java 中您可以调用
MyClass.newDefaultInstance()
另一种可能性是移动您指定默认值的位置:
如果您正在使用Spring 等框架使用反射来定位 0-arg 构造函数。
You might consider using a factory method:
Then from Java you can call
MyClass.newDefaultInstance()
Another possibility is to move where you specify the default values:
This style is especially useful if you're working with a framework such as Spring which uses reflection to locate a 0-arg constructor.
并不适合所有目的,但子类可能可以解决这个问题:
Not suitable for all purposes, but a subclass might do the trick:
如果我对这个问题的理解没有错误,那么下面的代码对我来说效果很好
``
If I am not wrong in understanding the question, following code worked very well for me`
`