No (not) Scala automatically created setters?

Google and my bad memory both give me hints of it, but every attempt is 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 that I am doing something wrong. (Also: please tell me that I am doing this wrong.)

EDIT

What I am not doing wrong, or at least not the only thing I am doing wrong, is how I call the installer. 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(my) // complains that I am passing in Int not a function 

I do this through SimplyScala because I'm too lazy and impatient to set up Scala on my tiny home machine. I hope this is not so ...

And the winner ...

Fabian, who pointed out that I cannot have a space between _ and =. I wondered why this should happen, and then it occurred to me:

The installer name for y not y_ , it is y_= !

Note:

 class Y { var y = 0 } var m = new Y() m.y_=(3) my 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_=) my res3: Int = 4 

Another successful day at StackExchange.

+4
source share
3 answers

This is true. They are just transparent.

my = 3

it actually accesses my through the setter method.

You can directly call m.y_=(3)

+8
source

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

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

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

If this is what you need, then you can do it by specifying f as follows:

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

... and then pass the setter to m as follows:

 f(m.y_=) 

If m would be a fresh instance of Y, then this will cause y on m to get the value 12. In the above snippet, m.y_ = is considered the value of the function. After it is passed, you can reference this function using the name setterter parameter. Since this is a function, you can apply it simply by passing it the parameter that it expects, which is a value of type Int.

+1
source
 class Y(var y : Int = 0) 

performs the task.

+1
source

Source: https://habr.com/ru/post/1338552/


All Articles