如何声明空列表然后在scala中添加字符串? [英] How to declare empty list and then add string in scala?
问题描述
我有这样的代码:
val dm = List[String]()
val dk = List[Map[String,Object]]()
.....
dm.add("text")
dk.add(Map("1" -> "ok"))
但它抛出运行时 java.lang.UnsupportedOperationException.
but it throws runtime java.lang.UnsupportedOperationException.
我需要声明空列表或空映射,以及一些稍后需要在代码中填充它们的地方.
I need to declare empty list or empty maps and some where later in the code need to fill them.
推荐答案
Scala 列表默认是不可变的.你不能添加"一个元素,但你可以通过在前面附加新元素来形成一个新列表.由于它是一个新列表,您需要重新分配引用(因此您不能使用 val).
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 new list, you need to reassign the reference (so you can't use a 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")
注意: 在 Scala 中,不要使用 Object
类型,而是使用 Any
、AnyRef
或 AnyVal
.
NB: In scala don't use the type Object
but Any
, AnyRef
or AnyVal
.
这篇关于如何声明空列表然后在scala中添加字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!