Search code examples
androidkotlinandroid-room

Kotlin: Unresolved reference to member function Intellisense suggests?


I am learning kotlin in android studio, and I must be making a syntax error.

I have the class:

abstract class RoomDB : RoomDatabase() {
   fun getInstance(context:Context) : RoomDB {
       // either finds an existing database or makes a new one
       // returns the database
   }
}

Later I am writing the following code:

import android.example.app.Database.RoomDB

class MainActivity : AppCompatActivity() {
    lateinit var database:RoomDB

    override fun onCreate(savedInstanceState: Bundle?) {
        database = RoomDB.getInstance(this)
    }
}

Autocomplete suggests the getInstance method; however, when I write this code, I get an unresolved reference error to this method. Any idea why?


Solution

  • At the suggestion of Slaw I put the method declaration inside of a companion object which fixed the compile errors. I do not understand why that fixed this.

    abstract class RoomDB : RoomDatabase() {
       companion object {
          fun getInstance(context:Context) : RoomDB {
              // either finds an existing database or makes a new one
              // returns the database
          }
       }
    }