Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Scala OOP question - pass by reference?

Tags:

oop

scala

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?

like image 512
Dominic Bou-Samra Avatar asked Aug 01 '11 08:08

Dominic Bou-Samra


People also ask

Is Scala pass by value or pass-by-reference?

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).

How can we pass argument to the method by reference?

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.

Is Scala pass by value?

By default scala use call-by-value for passing arguments to a function.

What is pass by value and pass-by-reference with example?

"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.


1 Answers

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).

like image 85
Debilski Avatar answered Oct 31 '22 18:10

Debilski