Basic Scala OOP question - pass by reference?

Viewed 14162

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?

4 Answers

Contrary to all the answers above, this in fact is quite doable in Scala without writing any special wrapper classes.

First you need to know that for any non-private class var, such as the ones used in the original question, Scala automatically generates getters and setters. So if we have a var called "color", Scala automatically creates a getter eponymously called "color" and a setter called "color_=".

Next you need to know that Scala lets you obtain a reference to any method by calling the special "_" method on it (which requires a space before it for disambiguation).

Finally putting these facts together, you can easily get a type-safe reference to any var's getter/setter and use that reference to dynamically set/get that var's value:

class Foo {
    var x = 0
}

object Foo {
    def setField[T](setter: T => Unit, value: T) {setter(value)}
    def getField[T](getter: () => T ) = {getter()}
}

val f = new Foo
val xsetter = f.x_= _
val xgetter = f.x _

Foo.setField(xsetter, 3)
println(f.x) //prints 3
println(Foo.getField(xgetter)) //prints 3
Related