Reputation: 31
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 to
new Soccer(n,Set(A,B,C))
Upvotes: 3
Views: 142
Reputation: 591
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)
}
}
Upvotes: 1
Reputation: 48400
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)
Upvotes: 2