Understanding Scala mutable set val reference -




in book "programming in scala", third edition, saw example not understand. understand it, typed scala interpreter:

scala> import scala.collection.mutable import scala.collection.mutable  scala> val movieset = mutable.set("hitch", "poltergeist") movieset: scala.collection.mutable.set[string] = set(poltergeist, hitch)  scala> movieset res3: scala.collection.mutable.set[string] = set(poltergeist, hitch)  <<< res3  scala> movieset += "shrek" res4: movieset.type = set(poltergeist, shrek, hitch)                  <<< res4 

my understanding when doing += on mutable.set, set should mutate in-place (i.e. variable assigned should not change), reference changed res3 res4. also, understood "val movieset" create value cannot changed. shouldn't cause "val movieset" remain res3 reference, , not change res4?

the res3 , res4 additional references same object, generated scala shell whenever type expression non-unit return type don't assign variable. when +=, method mutates set, , returns reference same object again, that's res3 , res4 end containing.

you can check 2 values same exact object (not 2 equal objects) using eq method. i.e., res3 eq movieset , res4 eq movieset should both true.

val restricts variable refer same object, not restrict object mutating in whatever way.





wiki

Comments

Popular posts from this blog

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -

Asterisk AGI Python Script to Dialplan does not work -