MurthyD
MurthyD

Reputation: 41

Why there is a different error message on using += and a=x+y on a val variable?

I had defined a val variable (t), and an array(m) with Int values and then tried to perform sum of all elements of array using for loop in two ways: case1. Using += (Error message: value += is not a member of Int ) case2. Using a=x+y way (Error message: reassignment to val )

Error is expected in this case as I'm trying to re-assign a new value to a val variable but why there is different error message in case1 and case2?

scala> val t = 0                                                                                                                              
t: Int = 0 

scala> val m = Array(1,2,3,4,5,6,7)                                                                                                           
n: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7)  

case1:

scala> for(e<-m) t+=e                                                                                                                         
<console>:28: error: value += is not a member of Int                                                                                          
       for(e<-m) t+=e                                                                                                                         
                  ^   

case2:

scala> for(e<-m) t=t+e                                                                                                                        
<console>:28: error: reassignment to val                                                                                                      
       for(e<-m) t=t+e                                                                                                                        
                  ^

Upvotes: 3

Views: 76

Answers (1)

Mario Galic
Mario Galic

Reputation: 48410

Consider the desugared version of t += 42 when t is a val:

t.$plus$eq(42)

Note how there is no assignment happening, instead, it is simply a method call on t. Contrast this with desugared version of t += 42 when t is a var and it does not have += method available

t = t.$plus(42)

Here we see an assignment statement. Therefore, as there is no assignment happening in the case of t+=e where t is a val, the error message does not indicate reassignment to val, instead it is complaining about missing method +=, that is, $plus$eq, on t.

Upvotes: 2

Related Questions