Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing varargs in a secondary constructor

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?

like image 540
rancidfishbreath Avatar asked Dec 04 '12 17:12

rancidfishbreath


1 Answers

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), .... 
like image 63
om-nom-nom Avatar answered Sep 21 '22 08:09

om-nom-nom