scala 如何声明空列表然后在scala中添加字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6557169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:09:26  来源:igfitidea点击:

How to declare empty list and then add string in scala?

scala

提问by rjc

I have code like this:

我有这样的代码:

val dm  = List[String]()
val dk = List[Map[String,Object]]()

.....

dm.add("text")
dk.add(Map("1" -> "ok"))

but it throws runtime java.lang.UnsupportedOperationException.

但它抛出运行时 java.lang.UnsupportedOperationException。

I need to declare empty list or empty maps and some where later in the code need to fill them.

我需要声明空列表或空映射,还有一些稍后在代码中需要填充它们的地方。

回答by paradigmatic

Scala lists are immutable by default. You cannot "add" an element, but you can form a new list by appending the new element in front. Since it is a newlist, you need to reassign the reference (so you can't use a val).

Scala 列表默认是不可变的。你不能“添加”一个元素,但你可以通过在前面附加新元素来形成一个新列表。由于它是一个列表,您需要重新分配引用(因此您不能使用 val)。

var dm  = List[String]()
var dk = List[Map[String,AnyRef]]()

.....

dm = "text" :: dm
dk = Map(1 -> "ok") :: dk

The operator ::creates the new list. You can also use the shorter syntax:

操作员::创建新列表。您还可以使用较短的语法:

dm ::= "text" 
dk ::= Map(1 -> "ok")

NB:In scala don't use the type Objectbut Any, AnyRefor AnyVal.

注意:在 Scala 中不要使用类型Objectbut Any, AnyRefor AnyVal

回答by Daniel C. Sobral

If you need to mutate stuff, use ArrayBufferor LinkedBufferinstead. However, it would be better to address this statement:

如果您需要改变内容,请使用ArrayBufferLinkedBuffer代替。但是,最好解决以下声明:

I need to declare empty list or empty maps and some where later in the code need to fill them.

我需要声明空列表或空映射,还有一些稍后在代码中需要填充它们的地方。

Instead of doing that, fill the list with code that returns the elements. There are many ways of doing that, and I'll give some examples:

不要那样做,而是用返回元素的代码填充列表。有很多方法可以做到这一点,我将举一些例子:

// Fill a list with the results of calls to a method
val l = List.fill(50)(scala.util.Random.nextInt)

// Fill a list with the results of calls to a method until you get something different
val l = Stream.continually(scala.util.Random.nextInt).takeWhile(x => x > 0).toList

// Fill a list based on its index
val l = List.tabulate(5)(x => x * 2)

// Fill a list of 10 elements based on computations made on the previous element
val l = List.iterate(1, 10)(x => x * 2)

// Fill a list based on computations made on previous element, until you get something
val l = Stream.iterate(0)(x => x * 2 + 1).takeWhile(x => x < 1000).toList

// Fill list based on input from a file
val l = (for (line <- scala.io.Source.fromFile("filename.txt").getLines) yield line.length).toList

回答by agilesteel

As everyone already mentioned, this is not the best way of using lists in Scala...

正如每个人已经提到的,这不是在 Scala 中使用列表的最佳方式......

scala> val list = scala.collection.mutable.MutableList[String]()
list: scala.collection.mutable.MutableList[String] = MutableList()

scala> list += "hello"
res0: list.type = MutableList(hello)

scala> list += "world"
res1: list.type = MutableList(hello, world)

scala> list mkString " "
res2: String = hello world

回答by gihanchanuka

As mentioned in an above answer, the Scala Listis an immutable collection. You can create an empty list with .empty[A]. Then you can use a method :+, +:or ::in order to add element to the list.

正如上面的回答中提到的,Scala List是一个不可变的集合。您可以创建一个空列表.empty[A]。然后你可以使用一个方法:++:或者::为了将元素添加到列表中。

scala> val strList = List.empty[String]
strList: List[String] = List()

scala> strList:+ "Text"
res3: List[String] = List(Text)

scala> val mapList = List.empty[Map[String, Any]]
mapList: List[Map[String,Any]] = List()

scala> mapList :+ Map("1" -> "ok")
res4: List[Map[String,Any]] = List(Map(1 -> ok))

回答by DaVinci

Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.htmlwhich has a += method.

scala 中的默认集合是不可变的,因此您有一个 + 方法,该方法返回一个新列表,其中添加了元素。如果你真的需要像 add 方法这样的东西,你需要一个可变集合,例如http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html它有一个 += 方法。

回答by Chalith Tharuka

Maybe you can use ListBuffers in scala to create empty list and add strings later because ListBuffers are mutable. Also all the List functions are available for the ListBuffers in scala.

也许您可以在 Scala 中使用 ListBuffers 创建空列表并稍后添加字符串,因为 ListBuffers 是可变的。Scala 中的 ListBuffers 也可以使用所有 List 函数。

import scala.collection.mutable.ListBuffer 

val dm = ListBuffer[String]()
dm: scala.collection.mutable.ListBuffer[String] = ListBuffer()
dm += "text1"
dm += "text2"
dm = ListBuffer(text1, text2)

if you want you can convert this to a list by using .toList

如果需要,可以使用 .toList 将其转换为列表

回答by Rom

In your case I use: val dm = ListBuffer[String]()and val dk = ListBuffer[Map[String,anyRef]]()

在你的情况下,我使用:val dm = ListBuffer[String]()val dk = ListBuffer[Map[String,anyRef]]()