title: Getting a Singleton in Kotlin
body: <p>I have been looking at some Google sample code and they seem to create a singleton using the the following code:</p>
  
  <pre><code>companion object {
  
          // For Singleton instantiation
          @Volatile
          private var instance: CarRepository? = null
  
          fun getInstance(carDao: CarDao) =
                  instance ?: synchronized(this) {
                      instance ?: CarRepository(carDao).also { instance = it }
                  }
      }
  </code></pre>
  
  <p>So I know <code>@Volatile</code> means that </p>
  
  <blockquote>
    <p>Marks the JVM backing field of the annotated property as volatile, meaning that writes to this field are immediately made visible to other threads.</p>
  </blockquote>
  
  <p>Should all Singletons instances always be marked as <code>@Volatile</code>? If so, why?</p>
  
  <p>Lastly, I don't understand the <code>getInstance</code> function</p>
  
  <pre><code>instance ?: synchronized(this) {
      instance ?: CarRepository(carDao).also { instance = it }
  }
  </code></pre>
  
  <p>What is it exactly doing here? </p>
  
  <p>UPDATE:
  Source: <a href="https://github.com/googlesamples/android-sunflower" rel="nofollow noreferrer">Google's Sunflower</a> 
  I changed the Repository and Dao name for my own use, but it is the same logic in the <code>Repository</code> files.</p>