Reputation: 13
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?
Upvotes: 1
Views: 104
Reputation: 11250
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
M
static in scala way using companion-objectobject 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)
}
B
b.v = new b.M(2)
You can find more info on inner classes at scala-lang.org
Upvotes: 3