Passing varargs in the secondary constructor

I have a class with a constructor that consists of Charset and vararg of type String. I want a convenience constructor with only vararg, which will call the main constructor with the default map and vararg.

class StringMessage(charset: Charset, frames: String*) { def this(frames: String*) = this(Charset.defaultCharset, frames) } 

Unfortunately, the class I showed two errors:

 called constructor definition must precede calling constructor 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 simulate this type of situation?

+6
source share
1 answer

I believe that :_* will work

 class StringMessage(charset: Charset, frames: String*) { def this(frames: String*) = this(Charset.defaultCharset, frames: _*) } 

It instructs the compiler to extend Seq, so it would look like you wrote:

 this(Charset.defaultCharset, frames(0), frames(1), .... 
+13
source

All Articles