F
F
foonfyrick2020-11-19 08:10:21
Kotlin
foonfyrick, 2020-11-19 08:10:21

Syncronized(this) Why can't I specify the key explicitly??

The code is the same, what is there that the key is the instance variable?

// здесь я указываю this, и когда на него навожу, у меня выделяется instance

    companion object{
        @Volatile
        var instance:MUserDatabase?=null
        fun getInstance(context: Context):MUserDatabase?{
            return instance ?: synchronized(this){
                val  tempInstance = Room.databaseBuilder(
                    context,
                    MUserDatabase::class.java,
                    "database"
                ).build()
                instance = tempInstance
                return instance
            }
        }
    }

// здесь я хочу явно указать instance но подсвечивается красным

    companion object{
        @Volatile
        var instance:MUserDatabase?=null
        fun getInstance(context: Context):MUserDatabase?{
            return instance ?: synchronized(instance){
                val  tempInstance = Room.databaseBuilder(
                    context,
                    MUserDatabase::class.java,
                    "database"
                ).build()
                instance = tempInstance
                return instance
            }
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-11-19
@foonfyrick

No, this in this case is a Companion object. You cannot synchronize on a nullable variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question