Scala:构造函数采用Seq或varargs [英] Scala: Constructor taking either Seq or varargs

查看:179
本文介绍了Scala:构造函数采用Seq或varargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我猜,为了兼容性原因,vararg参数 Any * 的类型是Array [Any] - 如果我错了,请更正。但是,这不解释以下错误:

 类Api(api_url:String,params:Seq [ ]){
def this(api_url:String,params:(String,String)*)
= this(api_url,params.seq)
}

此代码无法编译,但会显示警告:


double definition:
构造函数Api:(api_url:String,params:(String,String)*)Api和构造函数Api:(api_url:String,params:
Seq [ ])在第13行的Api在擦除后具有相同的类型:
(api_url:java.lang.String,params:Seq)Api


那么我如何定义一个构造函数取varargs或一个序列?

解决方案

一个序列,所以没有必要定义一个辅助构造函数或重载方法。



给定

 类Api(api_url:String,params: String,String)*)

你可以这样调用

  new Api(url,(a,b),(c,d))

  val seq = Seq (a,b),(c,d))
new Api(url,seq:_ *)
pre>

此外,在您的问题中,您正在params参数调用方法seq。这可能不会做你想要的。 seq用于确保对所得到的集合的操作是顺序地而不是并行地执行的。该方法是在Scala版本2.9.0中引入的并行集合。



你可能想使用的是toSeq,它返回使用的集合,一个Seq(或者如果它已经是一个Seq本身)。但是由于varargs参数已经输入为Seq,这是一个无操作。


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?

解决方案

A method taking varargs is also always taking a sequence, so there is no need to define an auxiliary constructor or overloaded method.

Given

class Api(api_url: String, params: (String, String)*)

you can call it like this

new Api("url", ("a", "b"), ("c", "d"))

or

val seq = Seq(("a", "b"), ("c", "d"))
new Api("url", seq:_*)

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.

这篇关于Scala:构造函数采用Seq或varargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆