views:

176

answers:

2

I seem to remember Scala treating methods ending in _= specially, so something like this:

object X { var x: Int = 0; def y_=(n : Int) { x = n }}

X.y = 1

should call X.y_=(1). However, in 2.8.0 RC1, I get an error message:

<console>:6: error: value y is not a member of object X
       X.y = 1
         ^

Interestingly, just trying to call the method without parentheses fails as well:

scala> X.y_= 1
<console>:1: error: ';' expected but integer literal found.
       X.y_= 1
             ^

Am I misremembering something which does actually exist or did I just invent it out of whole cloth?

+10  A: 

This is one of those corner cases in Scala. You cannot have a setter without a getter and vice versa.

The following works fine:

scala> object X {
     |   var x: Int = 0
     |   def y = x
     |   def y_=(n: Int) { x = n }
     | }
defined module X

scala> X.y = 45

scala> X.y
res0: Int = 45
missingfaktor
Ah, thanks! I'll try to remember it this time.
Alexey Romanov
You can certainly have the accessor without the mutator, just not a mutator without a corresponding accessor.
Randall Schulz
@Randall: Thanks, corrected. (Dunno what I was thinking when I wrote it.)
missingfaktor
+3  A: 
scala> object X { var x: Int = 0; def y_=(n : Int) { x = n }}
defined module X

scala>

scala> X y_= 1

scala> X.x
res1: Int = 1

scala> object X { var x: Int = _; def y = x ; def y_=(n: Int) { x = n } }
defined module X

scala> X.y = 1

scala> X.y
res2: Int = 1

scala>
Eastsun