How to access inner class elements in scala

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

1 answer

  • answered 2017-11-12 20:21 prayagupd

    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