Helen Zhao Helen Zhao - 3 months ago 13
Scala Question

Changing variable inside a class

class B(i:Int){
var v = new M(i)
class M(i: Int) {
val x = i
println("Creating a new M")
println(s"x = $x")
}
}


val b = new B(1)
val c = new B(2)
b.v = c.v


How do I change the variable v inside b with c.v and why can't I do this way?

Answer

The reason why you can't do such assignment is because M class is not static. Unlike java each outer class instance has it's own inner class so b.v and c.v are instance of different types hence you can't simple do assignment.

What you can do is to

  1. Declare M static in scala way using companion-object
object B {
  class M(i: Int) {
    val x = i
    println("Creating a new M")
    println(s"x = $x")
  }
}

class B(i:Int) {
  import B._
  var v = new B.M(i)
}
  1. Assign using same instance of class B
b.v = new b.M(2)

You can find more info on inner classes at scala-lang.org

Comments