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


You can add to immutable Seq

and reassign var

to result by writing

wordList :+= x.word

      



This expression is for desugars in wordList = wordList :+ word

the same way as x += 1

desugars for x = x + 1

.

+5


source


This will work:

wordList = wordList:+(x.word)

      

0


source


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

wordList = (x.word) :: wordList

This code solves it for everyone who is facing the same problem.

-1


source







All Articles