I have a class with a constructor which consists of a Charset and a vararg of type String. I want a convenience constructor with just the vararg that will call the main constructor with a the defaultCharset and the vararg.
class StringMessage(charset: Charset, frames: String*) {
def this(frames: String*) = this(Charset.defaultCharset, frames)
}
Unfortunately the class I have shown gives two errors:
called constructor's definition must precede calling constructor's definition
and
overloaded method constructor StringMessage with alternatives:
(frames: String*)mypackage.StringMessage <and>
(charset: java.nio.charset.Charset,frames: String*)mypackage.StringMessage
cannot be applied to (java.nio.charset.Charset, String*)
def this(frames: String*) = this(Charset.defaultCharset, frames)
^
What is the best way to model this type of situation?
I do believe that :_*
will work
class StringMessage(charset: Charset, frames: String*) {
def this(frames: String*) = this(Charset.defaultCharset, frames: _*)
}
It instructs compiler to expand Seq, so it would look like you wrote:
this(Charset.defaultCharset, frames(0), frames(1), ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With