Add element to Seq[String] in Scala

妖精的绣舞 提交于 2019-12-10 21:39:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!