Scala Immutable Set is Mutable when declaring as a var -
i'm in process of reading programming in scala, 2nd edition (fantastic book, much improve scala's website explaining things in non-rockety-sciencey manner) , noticed this...oddity when going on immutable , mutable sets.
it declares next immutable set
var jetset=set("boeing", "airbus") jetset+="lear" println(jetset.contains("cessna"))
and states mutable sets define += method. ok makes perfect sense. problem code works. , type of set created when tested in repl in fact immutable set, has += method defined on , functions fine. behold
scala> var = set("adam", "bill") a: scala.collection.immutable.set[string] = set(adam, bill) scala> += "colleen" scala> println(a) set(adam, bill, colleen) scala> a.getclass res8: class[_ <: scala.collection.immutable.set[string]] = class scala.collection.immutable.set$set3
but if declare set val, immutable set created does not have += method defined
scala> val b = set("adam", "bill") b: scala.collection.immutable.set[string] = set(adam, bill) scala> b += "colleen" <console>:9: error: value += not fellow member of scala.collection.immutable.set[string] b += "colleen"
what going on here? both stated immutable set 1 declared var has access += method , can utilize it.
also when kept calling getclass method on var immutable set noticed strange....
scala> a.getclass res10: class[_ <: scala.collection.immutable.set[string]] = class scala.collection.immutable.set$set3 scala> += "one" scala> a.getclass res12: class[_ <: scala.collection.immutable.set[string]] = class scala.collection.immutable.set$set4 scala> += "two" scala> a.getclass res14: class[_ <: scala.collection.immutable.set[string]] = class scala.collection.immutable.hashset$hashtrieset scala> += "tree" scala> a.getclass res16: class[_ <: scala.collection.immutable.set[string]] = class scala.collection.immutable.hashset$hashtrieset scala> res17: scala.collection.immutable.set[string] = set(one, tree, bill, adam, two, colleen)
my guess hidden syntactic sugar, scala recognizes it's var , allows replace newly constructed set anyway.
what's mutable not set
, reference it.
a += "colleen"
returns new immutable set, assigned mutable variable a
scala performs syntactic transformation, turning look into
a = + "colleen"
in case +=
not defined (as in case of immutable set
)
clearly +=
doesn't create sense when a
val
, since cannot reassign it, hence forbidden.
here's extract taken programming in scala (section 17.3)
to create easier switch immutable mutable collections, , vice versa, scala provides syntactic sugar. though immutable sets , maps not back upwards true +=
method, scala gives useful alternate interpretation +=
. whenever write a += b
, , a
not back upwards method named +=
, scala seek interpreting a = + b
if maintain reading in section, you'll find more thorough explanation, examples.
scala set immutability mutable
No comments:
Post a Comment