Scala extra no-arg constructor plus default constructor parameters

jkl picture jkl · Oct 28, 2010 · Viewed 8.5k times · Source

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!

Answer

Rex Kerr picture Rex Kerr · Oct 28, 2010

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.