Search code examples
kotlinobjectscopecompanion-object

How to reference outer object's property?


Consider the following code:

class SomeClass {

    companion object {
        val str = "My String"
        object AnotherObject {
             fun foo(str: String) {
                  return str + //companion object's str
             }
        }
    }
}

How to reference SomeClass::companion object::str from AnotherObject::foo?


Solution

  • Please try as follows:

    class SomeClass {
        companion object {
            val str = "My String"
            object AnotherObject {
                fun foo(str: String): String {
                    return str + SomeClass.str
                }
            }
        }
    }