Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not sure where my assignment is going

Tags:

scala

I ran into some issues today making assignments to a var field in a case class instance stored in a map. Here's a simple session in the repl demonstrating the problem:

scala> case class X(var x: Int)
defined class X

scala> val m = Map('x -> X(1))
m: scala.collection.immutable.Map[Symbol,X] = Map('x -> X(1))

scala> m
res0: scala.collection.immutable.Map[Symbol,X] = Map('x -> X(1))

scala> m('x).x = 7

scala> m
res1: scala.collection.immutable.Map[Symbol,X] = Map('x -> X(1))

scala> val x = m('x)
x: X = X(1)

scala> x.x = 7
x.x: Int = 7

scala> x
res2: X = X(7)

scala> m
res3: scala.collection.immutable.Map[Symbol,X] = Map('x -> X(7))

scala> m('x).x_=(8)

scala> m
res5: scala.collection.immutable.Map[Symbol,X] = Map('x -> X(8))

The first attempt at assignment does nothing. However, storing the instance in a val and then doing the assignment works, as does directly calling the assignment method for the field.

I'm using Scala 2.9.2.

If this is expected behavior, it would be nice if someone could explain it to me because I can't seem to make sense of it right now. If this is a bug then that would be good to know as well.

Either way, it would also be interesting to know where that first m('x).x = 7 assignment is going. I assume something is getting mutated somewhere—I just have no idea what that something could be.

Update: It looks like this only happens in the repl. I just tried compiling the code and the assignment happens as expected. So, what is the repl doing to my assignment?

like image 808
DaoWen Avatar asked Oct 21 '12 05:10

DaoWen


People also ask

What do you do if you don't understand your assignment?

If you still find that you don't fully understand the assignment, don't panic: you aren't required to tackle the prompt alone. Email your instructor and explain your confusion. Try to be as specific as possible. Are you confused about what you are being asked to do?


1 Answers

This seems to be a bug. If one executes this with a 2.10 nightly an error message is thrown:

scala> m('x).x = 7
<console>:10: error: ')' expected but string literal found.
 + "m(scala.Symbol("x")).x: Int = " + `$ires0` + "\n" 
                    ^

I created a ticket for this.

like image 101
kiritsuku Avatar answered Oct 31 '22 23:10

kiritsuku