Search code examples
androidkotlincompanion-object

Kotlin Companion Objection unresolved references


I have a Kotlin class with companion object which sees some fields of the parent class and does not see others. There is no option in Android Studio to import.

class A{
   var a = 1
   var b = 2
       companion object {
            a += 1// visible and imported
            b += 1// unresolved reference
       }
}

I do not want to create this variable inside the companion object.


Solution

  • You are absolutely incorrect.

    You cannot access members of class inside companion object at all. But you can use companion`s members in your class.

    If you see kotlin bytecode you will see that Companion object compiles to

       public static final class Companion {
          private Companion() {
          }
    
          // $FF: synthetic method
          public Companion(DefaultConstructorMarker $constructor_marker) {
             this();
          }
       }
    

    Since Companion is static class it can exist without class where it is declared.

    So in your case you can not access a and b because probably they are not exists.

    They are not accessable for you too, but probably you cought IDE bug and it doesnt give you error