I'm a little stumped at how silly this problem is and have a serious mindblank, but I thought I might ask anyway.
I have an object Foo, with several fields. I want a method that can change any of its fields depending on which one is passed in as a parameter. Like so:
class Foo {
var x = 0
var y = 0
}
class Bar {
def changeFooField(field : Int) = {
field = 1
}
}
Can I not use it like so?:
changeFooField(foo.x)
If not, how do I accomplish this?
In Java and Scala, certain builtin (a/k/a primitive) types get passed-by-value (e.g. int or Int) automatically, and every user defined type is passed-by-reference (i.e. must manually copy them to pass only their value).
Functions can be differentiated on the basis of parameters. And there are two ways to pass the parameters in functions: call by value and call by reference. C/C++ supports the call by reference because in the call by reference we pass the address of actual parameters in the place of formal parameters using Pointers.
By default scala use call-by-value for passing arguments to a function.
"Passing by value" means that you pass the actual value of the variable into the function. So, in your example, it would pass the value 9. "Passing by reference" means that you pass the variable itself into the function (not just the value). So, in your example, it would pass an integer object with the value of 9.
A common idiom is to pass an explicit setter method which takes care of changing the value.
class Foo {
var x = 0
var y = 0
}
class Bar {
def changeFooField(setter: (Int) => Unit) = {
setter(1)
}
}
val foo = new Foo
val bar = new Bar
bar.changeFooField(foo.x = _) // or equivalent: bar.changeFooField((i: Int) => foo.x = i)
assert(foo.x == 1)
(foo.x = _)
is a simple ad-hoc closure which allows write access to foo.x
. There is no need in adding this setter API to Foo
itself.
So, as it turns out, the setter method (foo.x=
– or rather foo.x_=
) is passed as an argument exactly as any other method is passed. You’ll have to remember that val
and var
in Scala don’t actually specify variables but create the methods which are then used to access the real (hidden) variables. (val
only creates a getter method, whereas var
of course creates both getter and setter).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With