Scala OOP基本问题-通过引用传递? [英] Basic Scala OOP question - pass by reference?

查看:188
本文介绍了Scala OOP基本问题-通过引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个问题有多愚蠢而感到困惑,并有严肃的头脑,但我想我还是会问.

I'm a little stumped at how silly this problem is and have a serious mindblank, but I thought I might ask anyway.

我有一个对象Foo,其中包含多个字段.我想要一种方法,该方法可以更改其任何字段,具体取决于将哪个字段作为参数传递.像这样:

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?

推荐答案

不,您不能.您需要将字段值封装到一个对象中:

No you cannot. You'll need to enclose the field value into an object:

class Field[T]( var value: T )

class Foo {
  val x = new Field(0)
  val y = new Field(0)
}

class Bar {
  def changeFooField( field: Field[Int] ) {
    field.value = 1
  } 
}

val f = new Foo
(new Bar).changeFooField( f.x )
println( f.x.value + " / " + f.y.value ) // prints "1 / 0"

这篇关于Scala OOP基本问题-通过引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆