0

I have a simple inner class variable, how do i access it in 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)
  }
}

The problem is that IntelliJ complains that it cannot resolve x, but when i run the program it works fine.enter image description here

Srinivas
  • 2,010
  • 7
  • 26
  • 51

1 Answers1

1

you can simply use .member_name to access variables in 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

since your example has x defined as mutable, you can change the value of x,

scala> i.x = 100
i.x: Int = 100

scala> i.x
res14: Int = 100

See working example - https://scastie.scala-lang.org/prayagupd/C9k9an4ASdaISnohbYQBmA

If you don't really need Outer to be a class, you can define it as singleton,

scala> object Outer {
     |             class Inner {
     |               var x = 1 //it can be val which is immutable
     |             }}
defined object Outer

then, simple instantiate Inner and access variables,

scala> val inner = new Outer.Inner
inner: Outer.Inner = Outer$Inner@4bcdd11

scala> inner.x
res2: Int = 1

Regarding not working on intellij, File | Invalidate Caches/Restart... should work

prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • This is simple, but can you please explain why this does not work in IntelliJ, thanks – Srinivas Nov 12 '17 at 20:26
  • The example is obviously working example. Try REPL which helps learning small stuffs in scala. What error you get in intellij? or What does intellij display x to be. update your question – prayagupa Nov 12 '17 at 20:28
  • in your example you are printing `i`, not `i.x` – prayagupa Nov 12 '17 at 20:30
  • Ok, this seems very odd, if i try println(i.x) the x is marked in red and IntelliJ says "cannot resolve symbol". But when I run the program, it works fine. – Srinivas Nov 12 '17 at 20:32
  • Run working code here https://scastie.scala-lang.org/prayagupd/C9k9an4ASdaISnohbYQBmA. Can you post the screenshot in question? – prayagupa Nov 12 '17 at 20:33
  • I have added the snapshot. Thanks. – Srinivas Nov 12 '17 at 20:39
  • I tried in intellij17 too, it does work for me. what your scala setup look like in intellij? I bet intellij is freaked out. Try [`File | Invalidate Caches/Restart...`](https://stackoverflow.com/a/5905931/432903). Also try running even with error. – prayagupa Nov 12 '17 at 20:45
  • Thanks it works file after I invalidated Caches/restart. I can see the variable – Srinivas Nov 12 '17 at 20:54
  • Awesome. Intellij is trash sometimes. – prayagupa Nov 12 '17 at 20:55