That's because "var v" is translated into a field, a getter and a setter. I'll take a small detour to explain that.
One important thing in Scala is preserving the interface, no matter if a field is defined with def, val or var, so it can change from one to the other without impact on the user code.
Also, a def can be overridden by a val on subclasses.
Now, while this would be easy to do if Scala was the only user code, it has to interface with Java as well. In Java, methods and fields are syntactically different, so any change from one to the other would break Java client code.
Therefore, what Scala actually does when you declare "var v" is to compile that into a v field, a v() method, and a v_= method.
Which is why you can't both declare "var v" and "def v". It's the same namespace.
But that's a confusion mostly made by Java programmers. Scala-wise, it's pretty simple: val, var and def are in the same namespace. Period.
On Tue, Jul 7, 2009 at 7:49 PM, Micha
<micha-1@...> wrote:
Hi,
one can define getters and setters without an associated field. But why does the
setter has to have the same name as the getter?
This compiles and works:
class X { private var v = 0; def get = v; def get_= (i:Int) { v = i } }
This compiles and gives a runtime error:
class X { private var v = 0; def get = v; def put_= (i:Int) { v = i } }
val k = new X
k: X = X@679e3bdd
scala> k.put = 3
<console>:6: error: value put is not a member of X
k.put = 3
which seems not true to me :-)
thanks for answering,
Michael
--
Daniel C. Sobral
Something I learned in academia: there are three kinds of academic reviews: review by name, review by reference and review by value.