Scala:采用 Seq 或 varargs 的构造函数
我猜测,出于兼容性原因,可变参数参数 Any*
的类型是 Array[Any] - 如果我错了,请更正。但是,这并不能解释以下错误:
class Api(api_url: String, params: Seq[(String, String)]) {
def this(api_url: String, params: (String, String)*)
= this(api_url, params.seq)
}
此代码无法编译,但给出警告:
双重定义: 构造函数 Api:(api_url: String, params: (String, String)*)Api 和构造函数 Api:(api_url: String, params: 第 13 行的 Seq[(String, String)])Api 删除后具有相同的类型: (api_url:java.lang.String,参数:Seq)Api
那么如何定义采用可变参数或序列的构造函数呢?
I am guessing that, for compatibility reasons, the type of vararg parameters Any*
is Array[Any] - please correct this if I'm wrong. However, this does not explain the following error:
class Api(api_url: String, params: Seq[(String, String)]) {
def this(api_url: String, params: (String, String)*)
= this(api_url, params.seq)
}
This code does not compile, but gives the warning:
double definition:
constructor Api:(api_url: String, params: (String, String)*)Api and constructor Api:(api_url: String, params:
Seq[(String, String)])Api at line 13 have same type after erasure:
(api_url: java.lang.String, params: Seq)Api
So how do I define a constructor taking either varargs or a sequence?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
采用可变参数的方法也始终采用序列,因此无需定义辅助构造函数或重载方法。
鉴于
您可以这样调用它
,或者
另外,在您的问题中,您正在对 params 参数调用方法 seq 。这可能不会达到您的预期。 seq 用于确保对结果集合的操作按顺序执行,而不是并行执行。该方法是在 Scala 2.9.0 版本中随并行集合引入的。
您可能想要使用的是 toSeq,它返回转换为 Seq 的集合(如果它已经是 Seq,则返回其本身)。但由于 varargs 参数已经被输入为 Seq,所以无论如何这都是一个空操作。
A method taking varargs is also always taking a sequence, so there is no need to define an auxiliary constructor or overloaded method.
Given
you can call it like this
or
Also, in your question, you are calling method seq on the params parameter. This probably does not do what you intended. seq is used to ensure that operations on the resulting collection are executed sequentially instead of in parallel. The method was introduced with the parallel collections in version 2.9.0 of Scala.
What you probably wanted to use was toSeq, which returns the collection it is used on converted to a Seq (or itself if it is already a Seq). But as varargs parameters are already typed as Seq, that is a no-op anyway.
不:实际上,
Any*
实际上与Seq[Any]
几乎相同,而不是与Array[Any]
相同。为了消除两者之间的歧义,您可以使用该技术添加一个虚拟隐式参数以使签名不同:
No: actually,
Any*
is actually almost identical toSeq[Any]
, not toArray[Any]
.To disambiguate between the two, you can use the technique to add a dummy implicit parameter to make the signature different:
我想您想让方法调用更漂亮,因此使用
_*
显式调用不是一个选项。在这种情况下,您可以通过方法重载来解决问题。I suppose that you would like to make the method calls prettier and so explicit calling with
_*
is not an option. In that case you may solve the problem with method overloading.