[英]Scala: Appending an Element to a List
I have the following 2 code snippets; 我有以下2个代码片段; the first one gives me no trouble, but for the second one (appending to the list in a function), I'm getting an error message.
第一个给了我没有麻烦,但对于第二个(附加到函数中的列表),我收到一条错误消息。 What's the difference between these 2, and how do I fix the second one?
这两者之间有什么区别,我该如何修复第二个?
This one works fine: 这个工作正常:
object MyApp extends App
{
var myList = List.range (1, 6)
myList ::= 6
println(myList)
}
This doesn't work: 这不起作用:
def myFunc(list:List[Int]):Unit =
{
list ::= 10
}
error: value ::= is not a member of List[Int]
list ::= 10
^
one error found
Variables marked with var
are mutable and so can be reassigned. 标有
var
变量是可变的,因此可以重新分配。 The a ::= b
operator is simply syntactic sugar provided by the compiler for var
variables . a ::= b
运算符只是编译器为var
变量提供的语法糖 。 It performs the operation a = b :: a
. 它执行操作
a = b :: a
。 Here is an example: 这是一个例子:
scala> var l1 = List(1,2,3)
l1: List[Int] = List(1, 2, 3)
scala> l1 ::= 4
scala> l1
res1: List[Int] = List(4, 1, 2, 3)
scala> val l2 = List(1,2,3)
l2: List[Int] = List(1, 2, 3)
scala> l2 ::= 4
<console>:9: error: value ::= is not a member of List[Int]
l2 ::= 4
^
scala> val l3 = 4 :: l2
l3: List[Int] = List(4, 1, 2, 3)
Passed parameters are not mutable so the ::=
operator cannot be used. 传递的参数不可变,因此不能使用
::=
运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.