我正在尝试在 Scala 中创建一个单词列表。我是这门语言的新手。我已经阅读了很多关于如何不能编辑不可变对象(immutable对象)的帖子,但没有一篇能够向我展示如何在 Scala 中创建我需要的列表。我正在使用 var 进行初始化,但这没有帮助。
var wordList = Seq.empty[String]
for (x <- docSample.tokens) {
wordList.++(x.word)
}
println(wordList.isEmpty)
我将不胜感激对此的一些帮助。我知道对象在 Scala 中是不可变的(尽管 vars 不是),但我需要的是一些简明信息,说明为什么上面总是打印“true”,以及如何使列表添加 docSample.tokens.word 中包含的单词.
最佳答案
您可以使用 val 并仍然保持单词列表不可变,如下所示:
val wordList: Seq[String] =
for {
x <- docSample.tokens
} yield x.word
println(wordList.isEmpty)
或者:
val wordList: Seq[String] = docSample.tokens.map(x => x.word)
println(wordList.isEmpty)
甚至:
val wordList: Seq[String] = docSample.tokens map (_.word)
println(wordList.isEmpty)
关于java - 在 Scala 中向 Seq[String] 添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26579853/