Inner object in class cannot close over outer class members


#1

Another question in the same vein of my previous, and linked to it.

The following won’t compile

open class A (val str:String){
    object R {
        //val s1 = str // str is not in scope!
        val s2 = "foo"
    }
    fun foo() {
        val ss = R.s2 // won't compile unless A.R is imported!
    }
}

class B : A(“x”) {
  fun foo() {
  val ss = R.s2 // won’t compile unless A.R is imported!
  }
}


while:

open class A (val str:String){
    val R = object {
        val s = str // compiles
    }
}

class B : A(“x”) {
  fun foo() {
  val ss = R.s2 // won’t compile since A.R is Any
  }
}

So, it looks like inner object declarations are like static members of the class definition; this is consistent with inner class definitions, that require the inner modifier to close over the outer class' fields; however, there is no inner modifier for object definitions, and object expressions are resolved as Any; do you think part of this behavior may qualify as a bug?

Thanks !


#2

In Java and Kotlin, "inner" means "capturing the outer instance", where as "nested" means simply declared inside something else. Java's static classes are only nested, non-static nested classes are inner. In Kotlin you have to explicitly declare something as "inner" (we reversed the Java's convention). So, your object is not inner, btu only nested. And no named object can be inner, in fact: named objects are singletons, so the can not depend on any kind of outer instance.