2014-10-27 513 views
3

我试图在Scala中创建单词列表。我是新来的语言。我已经阅读了很多关于如何编辑不可变对象的文章,但没有一篇能够告诉我如何在Scala中创建我需要的列表。我正在使用var来初始化,但这没有帮助。将元素添加到Scala中的Seq [String]

var wordList = Seq.empty[String] 

for (x <- docSample.tokens) { 
    wordList.++(x.word) 
} 

println(wordList.isEmpty) 

我将不胜感激这一些帮助。我明白在Scala中对象是不可变的(虽然变量不是),但我需要的是关于为什么上述总是打印“真”的一些简明信息,以及如何让列表添加docSample.tokens.word中包含的单词。

+4

听起来像是你想要的东西像'val wordList = docSample.tokens.map(_。word)'不需要可变变量。或'flatMap',如果'word'碰巧是另一个'Seq' ..从你的帖子中不清楚。 – 2014-10-27 01:23:09

回答

-1

几个小时后,我发布了一个问题,一分钟后发现问题。

单词表=(x.word)::单词表

此代码解决它的人谁在同样的问题就来了。

+0

这里没有必要使用可变的'var' wordList。 – 2014-10-27 07:27:28

5

您可以附加到一个不变的Seq通过写

wordList :+= x.word 

重新分配var的结果是,表达desugars到wordList = wordList :+ word以同样的方式,x += 1 desugars到x = x + 1

8

您可以使用VAL,仍然保持词表不变是这样的:

val wordList: Seq[String] = 
    for { 
    x <- docSample.tokens  
    } yield x.word 

println(wordList.isEmpty) 

或者:

val wordList: Seq[String] = docSample.tokens.map(x => x.word)  

println(wordList.isEmpty) 

甚至:

val wordList: Seq[String] = docSample.tokens map (_.word)  

println(wordList.isEmpty) 
0

这将工作:

wordList = wordList:+(x.word)