Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List Scala中元组列表项的动态添加_List_Scala_Tuples - Fatal编程技术网

List Scala中元组列表项的动态添加

List Scala中元组列表项的动态添加,list,scala,tuples,List,Scala,Tuples,如何使用Scala在元组的ListBuffer中使用循环添加项? 我已宣布名单如下: val listV = new ListBuffer[(String,Int)](); 在添加这样的项目时: listV += ("a",1) 给出错误:类型不匹配,如下所示 [error] found : String("a") [error] required: (String, Int) [error] listV += ("a",1) [error]

如何使用Scala在元组的ListBuffer中使用循环添加项? 我已宣布名单如下:

val listV = new ListBuffer[(String,Int)]();
在添加这样的项目时:

listV += ("a",1)
给出错误:类型不匹配,如下所示

[error]  found   : String("a")

[error]  required: (String, Int)

[error]         listV += ("a",1)

[error]                   ^

[error] one error found

有什么建议可以解决这个问题吗?感谢您的期待

+=
ListBuffer
上的一个方法,因此scala编译器认为您试图将两个参数传递给
+=
方法。您需要一组额外的括号来强调元组是单个元素,而不是无效的参数列表

listV += (("a", 1))

+=
ListBuffer
上的一个方法,因此scala编译器认为您试图将两个参数传递给
+=
方法。您需要一组额外的括号来强调元组是单个元素,而不是无效的参数列表

listV += (("a", 1))
更多的括号
(“a”,1)
被解释为在
列表v
中添加
字符串和
Int

scala> val listV = new ListBuffer[(String, Int)]
listV: scala.collection.mutable.ListBuffer[(String, Int)] = ListBuffer()

scala> listV += (("a", 1))
res0: listV.type = ListBuffer((a,1))
更多的括号
(“a”,1)
被解释为在
列表v
中添加
字符串和
Int

scala> val listV = new ListBuffer[(String, Int)]
listV: scala.collection.mutable.ListBuffer[(String, Int)] = ListBuffer()

scala> listV += (("a", 1))
res0: listV.type = ListBuffer((a,1))

您可以使用编译器可能与函数调用混淆的以下语法:

listV += "a" -> 1
如果您更习惯于在元组周围始终使用大括号,这也将得到正确的解释

listV += ("a" -> 1)

您可以使用编译器可能与函数调用混淆的以下语法:

listV += "a" -> 1
如果您更习惯于在元组周围始终使用大括号,这也将得到正确的解释

listV += ("a" -> 1)

考虑把答案标记为正确,这样这个问题并没有得到回答。