问题
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.
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.
回答1:
You can use a val and still keep the wordlist immutable like this:
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)
回答2:
You can append to an immutable Seq
and reassign the var
to the result by writing
wordList :+= x.word
That expression desugars to wordList = wordList :+ word
in the same way that x += 1
desugars to x = x + 1
.
回答3:
This will work:
wordList = wordList:+(x.word)
回答4:
After a few hours, I posted a question, and a minute later figured it out.
wordList = (x.word)::wordList
This code solves it for anyone who comes across the same problem.
来源:https://stackoverflow.com/questions/26579853/add-element-to-seqstring-in-scala