Scala methods ending in _=
Asked Answered
H

2

7

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?

Humbuggery answered 4/5, 2010 at 13:4 Comment(0)
O
13

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
Oosperm answered 4/5, 2010 at 13:11 Comment(2)
You can certainly have the accessor without the mutator, just not a mutator without a corresponding accessor.Alleras
@Randall: Thanks, corrected. (Dunno what I was thinking when I wrote it.)Oosperm
D
3
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>
Discommend answered 4/5, 2010 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.