gpt4 book ai didi

java - Scala 中具有多个参数的辅助构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:20 26 4
gpt4 key购买 nike

我有一个用整数和集合初始化的类。我想创建一个带有整数和多个参数的辅助构造函数。这多个参数应该是集合的内容。

我需要帮助使用合适的参数调用主构造函数。

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)应该等价于new Soccer(n,Set(A,B,C))

最佳答案

尝试定义 factory apply method在伴随对象上而不是像这样辅助构造函数

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

现在像这样构建Soccer

Soccer(n,A,B,C)

关于java - Scala 中具有多个参数的辅助构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58034005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com