我有一个简单的内部类变量,我如何在scala中访问它?
class Outer {
class Inner {
var x = 1
}}
object Main {
def main(args: Array[String]): Unit = {
val o = new Outer
val i = new o.Inner
println(i.x)
}
}
答案 0 :(得分:1)
您只需使用.member_name
来访问scala中的变量。
scala> class Outer {
class Inner {
var x = 1 //it can be val which is immutable
}}
defined class Outer
scala> val o = new Outer
o: Outer = Outer@358b0b42
scala> val i = new o.Inner
i: o.Inner = Outer$Inner@512f2c7d
scala> i.x
res13: Int = 1
由于您的示例将x定义为可变,因此您可以更改x
,
scala> i.x = 100
i.x: Int = 100
scala> i.x
res14: Int = 100
参见工作示例 - https://scastie.scala-lang.org/prayagupd/C9k9an4ASdaISnohbYQBmA
如果你真的不需要Outer成为一个班级,你可以将其定义为单身,
scala> object Outer {
| class Inner {
| var x = 1 //it can be val which is immutable
| }}
defined object Outer
然后,简单地实例化内部和访问变量,
scala> val inner = new Outer.Inner
inner: Outer.Inner = Outer$Inner@4bcdd11
scala> inner.x
res2: Int = 1
关于不使用intellij, File | Invalidate Caches/Restart...应该正常工作