0

What is the difference between simply = assignment and also when getting an instance? It seems that I am not catching some subtle points.

fun getInstance() = instance ?: synchronized(this){
            instance ?: FakeDatabase().also { instance = it }
        }

And

 fun getInstance() = instance ?: synchronized(this){
            instance = FakeDatabase()
        }
ADM
  • 20,406
  • 11
  • 52
  • 83
Swallacova
  • 37
  • 4

2 Answers2

2

The first major difference is returned value.

  1. First method will return and instance of FakeDatabase because of Elvis Operator. it will return instance if not null or create one and assign it to instance and return.

  2. Second method is not returning anything You can check it by calling it . it will return an Unit because you only have an assignment statement here. You can make it work by adding returned value for synchronize block at last line .

     fun getInstance() = instance ?: synchronized(this) {
         instance = FakeDatabase()
         instance!!
     }
    

But this just for demonstration purpose you can concise is as follows. You do not need ?: inside again.

fun getInstance() = instance ?: synchronized(this) {
         FakeDatabase().also {  instance = it }
    }

If you have doubt about also its just an Scoping function. It allows to perform operation on an object and its return the same Object. in this case a FakeDatabase object after assigning it to instance.

ADM
  • 20,406
  • 11
  • 52
  • 83
1

It is double check pattern (https://en.wikipedia.org/wiki/Double-checked_locking) written in kotlin. Then you got the lock, might be second thread already create instance. If it didn't - you create FakeDatabase() for return and also set it into instance variable