Scala额外的无参数构造函数以及默认构造函数参数 [英] Scala extra no-arg constructor plus default constructor parameters

查看:85
本文介绍了Scala额外的无参数构造函数以及默认构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在构造函数上使用Scala 2.8默认参数,出于Java兼容性的原因,我想要一个使用默认参数的无参数构造函数.

出于非常明智的原因,这行不通:

  class MyClass(field1:String ="foo",field2:String ="bar"){def this()= {this()//<-不编译,但是如何不复制默认值?}} 

我想知道是否有任何我想念的东西.有什么想法不需要复制默认参数吗?

谢谢!

解决方案

我不会真的推荐它,但是您可以通过向构造函数添加另一个参数来做到这一点:

  class MyClass(a:字符串="foo",b:字符串="bar",u:单位=()){def this(){this(u =())}} 

Unit 是一个不错的选择,因为无论如何您只能将一件事传递给它,因此显式传递默认值不会有任何错误的可能性,但是它可以让您调用正确的构造函数

如果您只想复制一个的默认值,则可以使用相同的策略,只是覆盖选择的一个默认值,而不添加单位参数.

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!

解决方案

I wouldn't really recommend it, but you can do it by adding another parameter to your constructor:

class MyClass(a: String = "foo", b: String = "bar", u: Unit = ()) {
  def this() { this(u = ()) }
}

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.

这篇关于Scala额外的无参数构造函数以及默认构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆