Add item to Seq [String] in Scala
I am trying to create a list of words in Scala. I am new to the language. I have read many posts about how you cannot edit immutable objects, but none of them have been able to show me how to create the list I need in Scala. I am using var for initialization, but it doesn't help.
var wordList = Seq.empty[String]
for (x <- docSample.tokens) {
wordList.++(x.word)
}
println(wordList.isEmpty)
I would really appreciate help with this. I understand that objects are immutable in Scala (although vars doesn't), but I need a quick summary of why the above always prints "true", and how I can make the list by adding the words contained in docSample.tokens.word.
+3
source to share
4 answers
You can use val and still keep the wordlist unchanged like this:
val wordList: Seq[String] =
for {
x <- docSample.tokens
} yield x.word
println(wordList.isEmpty)
As an alternative:
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)
+8
source to share