Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Appending an Element to a List

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
like image 274
user1888243 Avatar asked Mar 09 '23 22:03

user1888243


1 Answers

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.

like image 174
evan.oman Avatar answered Mar 31 '23 09:03

evan.oman