I have the following 2 code snippets; 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. The a ::= b
operator is simply syntactic sugar provided by the compiler for var
variables. It performs the operation 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With