Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't (didn't) Scala have automatically generated setters?

Tags:

scala

Google and my failing memory are both giving me hints that it does, but every attempt is coming up dry.

class Y {
    var y = 0
}
var m = new Y()
m.y_(3)

error: value y_ is not a member of Y

Please tell me I am doing something wrong. (Also: please tell me what it is I am doing wrong.)

EDIT

The thing I am not doing wrong, or at least not the only thing I am doing wrong, is the way I am invoking the setter. The following things also fail, all with the same error message:

m.y_ // should be a function valued expression
m.y_ = (3) // suggested by Google and by Mchl
f(m.y_) // where f takes Int => Unit as an argument
f(m.y)  // complains that I am passing in Int not a function

I am doing this all through SimplyScala, because I'm too lazy and impatient to set up Scala on my tiny home machine. Hope it isn't that...

And the winner is ...

Fabian, who pointed out that I can't have a space between the _ and the =. I thought out why this should be and then it occurred to me:

The name of the setter for y is not y_, it is y_= !

Observe:

class Y {
     var y = 0
}
var m = new Y()
m.y_=(3)
m.y
res1: Int = 3
m.y_=
error: missing arguments for method y_= in class Y;
follow this method with `_` if you want to treat 
it as a partially applied function
       m.y_=
         ^
m.y_=_
res2: (Int) => Unit = 
def four(f : Int => Unit) = f(4) 
four(m.y_=)

m.y
res3: Int = 4

Another successful day on StackExchange.

like image 756
Michael Lorton Avatar asked Dec 29 '22 01:12

Michael Lorton


2 Answers

It does. They're just transparent.

m.y = 3

this actually accesses the m.y through a setter method.

Directly you can call m.y_=(3)

like image 68
Mchl Avatar answered Jan 22 '23 23:01

Mchl


It's a little hard to judge from your examples, but it seems you were trying to pass the setter to a function that would then set a value on it. That is, looking at this:

f(m.y_) // where f takes Int => Unit as an argument
f(m.y)  // complains that I am passing in Int not a function

... suggests that there is a function f in which you want to set a value using the setter passed in.

If that's what you were after, then you can get it done by defining f like this:

def f(setter: Int => Unit) = setter(12)

... and then pass the setter on m like this:

f(m.y_=)

If m would be a fresh instance of Y, then this would result in y on m getting set to 12. In the snippet above, m.y_= is considered a function value. Once it is passed in, you can reference the function using the parameter name setter. Since it's a function, you can apply it simply by passing it the parameter it expects, which is a value of type Int.

like image 25
Wilfred Springer Avatar answered Jan 22 '23 23:01

Wilfred Springer