在 Scala 中将元素添加到 Seq[String]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26579853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:39:21  来源:igfitidea点击:

Add element to Seq[String] in Scala

javalistscalaseq

提问by user3297367

I'm trying to create a list of words in Scala. I'm new to the language. I have read a lot of posts about how you can't edit immutable objects, but none that has managed to show me how to create the list I need in Scala. I am using var to initialise, but this isn't helping.

我正在尝试在 Scala 中创建一个单词列表。我是语言的新手。我已经阅读了很多关于如何不能编辑不可变对象的帖子,但没有一篇文章能够向我展示如何在 Scala 中创建我需要的列表。我正在使用 var 进行初始化,但这无济于事。

var wordList = Seq.empty[String]

for (x <- docSample.tokens) {
  wordList.++(x.word)
}

println(wordList.isEmpty)

I would greatly appreciate some help with this. I understand that objects are immutable in Scala (although vars are not), but what I need is some concise information about why the above always prints "true", and how I can make the list add the words contained in docSample.tokens.word.

我将不胜感激。我知道对象在 Scala 中是不可变的(尽管 vars 不是),但我需要的是一些关于为什么上面总是打印“true”的简明信息,以及如何让列表添加包含在 docSample.tokens.word 中的单词.

回答by Carl

You can use a val and still keep the wordlist immutable like this:

您可以使用 val 并且仍然保持 wordlist 不变,如下所示:

val wordList: Seq[String] = 
  for {
    x <- docSample.tokens     
  } yield x.word

println(wordList.isEmpty)

Alternatively:

或者:

val wordList: Seq[String] = docSample.tokens.map(x => x.word)     

println(wordList.isEmpty)

Or even:

甚至:

val wordList: Seq[String] = docSample.tokens map (_.word)     

println(wordList.isEmpty)

回答by Chris Martin

You can append to an immutable Seqand reassign the varto the result by writing

您可以附加到不可变对象Seqvar通过编写将 重新分配给结果

wordList :+= x.word

That expression desugars to wordList = wordList :+ wordin the same way that x += 1desugars to x = x + 1.

该表达式 desugars towordList = wordList :+ word的方式与x += 1desugars to相同x = x + 1

回答by Bipp

This will work:

这将起作用:

wordList = wordList:+(x.word)

回答by user3297367

After a few hours, I posted a question, and a minute later figured it out.

几个小时后,我发布了一个问题,一分钟后我想通了。

wordList = (x.word)::wordList

wordList = (x.word)::wordList

This code solves it for anyone who comes across the same problem.

此代码为遇到相同问题的任何人解决了它。