Angelina
Angelina

Reputation: 1583

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.

Upvotes: 1

Views: 5714

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170815

Android Studio imported A class variables. In imports i see import package.A.a, but not import package.A.b

import package.A.a simply doesn't make sense for a class property a, and companion object wouldn't require an import from the class it's companion to anyway. My best guess is that it's importing from an object in a different package.

Upvotes: 0

Andrey Danilov
Andrey Danilov

Reputation: 6602

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

Upvotes: 4

Samuel Eminet
Samuel Eminet

Reputation: 4737

You cannot access instance variables from static context (companion), this is the same as Java code

Upvotes: 0

Related Questions