在Scala中将元素添加到Seq [String] [英] Add element to Seq[String] in Scala

查看:5000
本文介绍了在Scala中将元素添加到Seq [String]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Scala中创建单词列表.我是这门语言的新手.我已经阅读了很多关于如何无法编辑不可变对象的文章,但是没有一篇文章向我展示了如何在Scala中创建所需的列表.我正在使用var进行初始化,但这无济于事.

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)

对此我将不胜感激.我知道对象在Scala中是不可变的(尽管var不是),但是我需要的是一些简洁的信息,以了解上面的内容为何始终显示"true",以及如何使列表添加docSample.tokens.word中包含的单词.

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.

推荐答案

您可以使用val并仍然保持单词表不变,如下所示:

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)

或者:

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

println(wordList.isEmpty)

甚至:

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

println(wordList.isEmpty)

这篇关于在Scala中将元素添加到Seq [String]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆