3

I have a class that is initialized with an integer and a set. I want to create an auxiliary constructor that takes an integer and multiple parameters. These multiple parameters should be the contents of the set.

I need help calling the primary constructor with suitable arguments.

final class Soccer[A](max: Int, collection_num: Set[A]) {

///Auxiliary Constructor
/// new Soccer(n,A,B,C)` is equivalent to `new Soccer(n,Set(A,B,C))`.
///This constructor requires at least two candidates in order to avoid ambiguities with the
/// primary constructor.

def this(max: Int, first: A, second: A, other: A*) = {
///I need help calling the primary constructor with suitable arguments.
}

}

new Soccer(n,A,B,C)should be equivalent tonew Soccer(n,Set(A,B,C))

2 Answers2

2

Try defining factory apply method on the companion object instead of auxiliary constructor like so

object Soccer {
  def apply[A](max: Int, first: A, second: A, other: A*): Soccer[A] = {
    new Soccer(max, Set[A](first, second) ++ other.toSet)
  }
}

Now construct Soccer like so

Soccer(n,A,B,C)
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
1

Using the apply method in companion object is a good way to achieve the requirement, but if you really want to do it in auxiliary constructor, you just call the this method like:

final class Soccer[A](max: Int, collection_num: Set[A]) {
  def this(max: Int, first: A, second: A, other: A*) = {
    this(max, Set[A](first, second) ++ other.toSet)
  }
}
Pritish
  • 591
  • 3
  • 9