开发者

Scala passing a reference to this class

I have a class, with multipl开发者_Go百科e methods and members. When I create an instance of this class, I create an instance of another class within the first class. Some of the methods in this second class require to know which instance of the first class is running. Currently, I am trying to pass "this" into the argument that accepts type firstClass. What am I doing wrong? Again, I simply want the second class instance knowing what first class instance it belongs to so that it can call public methods and members from it.

EDIT: Code example:

def main(args:Array[String]) : Unit = {
  val objectOne = new classOne
}

class classOne {
  val mutableBuffer = mutable.Buffer[String]
  val objectTwo = new classTwo

  objectTwo.doThis(this)
}

class classTwo {
  def doThis (exA:classOne) = {
    exA.mutableBuffer += "Adding text to a Buffer in object One"
  }
}


Self-typing is often the cleanest solution here

class Bippy {
  outer =>
  ...
  class Bop {
    def demoMethod() = println(outer)
  }
  ...
}

UPDATE

The example code changes everything, this clearly isn't about inner classes. I believe your problem is in this line:

val mutableBuffer = mutable.Buffer[String]

It isn't doing what you think it's doing, mutableBuffer is now pointing to the mutable.Buffer singleton, it isn't actually an instance of a Buffer

Instead, try one of these two:

val mutableBuffer = mutable.Buffer[String]()
//or
val mutableBuffer = mutable.Buffer.empty[String]

You should also stick to the convention of starting class/singleton/type names with an uppercase letter, turning your example code into:

import collection.mutable.Buffer

def main(args:Array[String]) : Unit = {
  val one = new ClassOne()
}

class ClassOne {
  val mutableBuffer = Buffer.empty[String]
  val two = new ClassTwo()

  two.doThis(this)
}

class ClassTwo {
  def doThis(one: ClassOne) = {
    one.mutableBuffer += "Adding text to a Buffer in object One"
  }
}


I had to make some superficial changes to your example code in order to make it run:

import scala.collection.mutable

class classOne {
  val mutableBuffer : mutable.Buffer[String] = new mutable.ArrayBuffer[String]
  val objectTwo = new classTwo

  objectTwo.doThis(this)
}

class classTwo {
  def doThis (exA : classOne) = {
    exA.mutableBuffer += "Adding text to a Buffer in object One"
  }
}

val objectOne = new classOne
println(objectOne.mutableBuffer(0))

But it works as expected. The classTwo object is able to modify the classOne object. Do you need something beyond this functionality?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜