Scala: adding an item to a list

I have the following 2 code snippets; the first of them does not give me any problems, but for the second (adding to the list in the function) I get an error message. What is the difference between the two, and how can I fix the second?

This works well:

object MyApp extends App { var myList = List.range (1, 6) myList ::= 6 println(myList) } 

This does not work:

 def myFunc(list:List[Int]):Unit = { list ::= 10 } error: value ::= is not a member of List[Int] list ::= 10 ^ one error found 
+5
source share
2 answers

I assume that you are a Java programmer, and that is why you have a problem in order to understand what the problem is. In Java, if you try to change the list, even in a method, you can do this because a new collection is not created; This is a collection with an added item.

However, in Scala, since the list itself is not changed, then a completely new list needs to be created, and therefore a reassignment of the variable pointing to the list is required. Since in Scala, the val values ​​passed in the arguments, this reassignment causes a problem. A new list is created in your first code, but since list is var, this reassignment does not cause problems.

If the List itself was changed, then you would not have problems in the second block of code, since you did not need to reassign the list. To prove this point, use ListBuffer instead of List in the second block of code, and you will see that it works fine.

+2
source

Variables marked with var are mutable and therefore can be reassigned. The operator a ::= b is just the 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) 

The passed parameters are not changed, therefore the ::= operator cannot be used.

+6
source

Source: https://habr.com/ru/post/1263886/


All Articles