本文介绍了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)
}

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

那么我如何定义一个构造函数取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:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:07