Add element to Seq[String] in Scala

11,426

Solution 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)

Solution 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.

Share:
11,426
user3297367
Author by

user3297367

Updated on July 30, 2022

Comments

  • user3297367
    user3297367 almost 2 years

    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.