我有一个带输入参数的函数:数字和字符串列表,例如:(1,ListString)
我需要它返回一个新的字符串列表,如下所示:
[["1","name1"], ["1","name2"]]
对于输入字符串列表中的每个字符串,我需要将其放在该结构中,因此我构建了以下内容:
def buildStringForproductsByCatView(tenantId:String, cat:List[String]):List[String]=
{
var tempList= List[String]()//(cat.foreach(x => "[[\"1\",\""+x+"\"]]"))
cat.foreach(x => println(("[[\"1\",\""+x+"\"]]")))
cat.foreach(x => tempList + ("[[\"1\",\""+x+"\"]]"))
println(tempList.mkString(","))
tempList
}
列表中没有填充项目,我尝试了几种方法,但无法得到它。
打印线工作正常,我得到了这个:
[["1","1"]]
[["1","cat1"]]
我只想将它们添加到一个新的字符串列表中。
答案 0 :(得分:2)
您的代码中存在两个错误的内容。
首先,要将项目附加到列表,您应该使用:+
。 +
不是你想要的。 tempList + "asd"
隐式将列表转换为String,并将文本附加到此字符串。这可能令人困惑。
第二个List
是不可变的,因此每个:+
调用都会返回一个新列表。
所以你的代码应该是这样的:
x => tempList = tempList :+ ("[[\"1\",\""+x+"\"]]")
答案 1 :(得分:2)
虽然其他两个答案在技术上是正确的,但我不明白为什么你不使用map:
def buildString4ProductsByCatView(tenantId:String, cat:List[String]) = {
cat.foreach(x => println(("[[\"1\",\""+x+"\"]]")))
cat.map(x => "[[\"1\",\"" + x + "\"]]")
}
答案 2 :(得分:0)
解决方案是将ListBuffer [String]与append一起使用,最后使用toList:
def buildStringForproductsByCatView(tenantId:String, cat:List[String]):List[String]=
{
cat.foreach(x => println(("[[\"1\",\""+x+"\"]]")))
val langItems = ListBuffer[String]()
cat.foreach(x => langItems.append(("[[\"1\",\""+x+"\"]]")))
langItems.toList
}