Christophe Beyls
1 min readJul 30, 2020

--

Yes, there are different ways to write this in Kotlin, I just chose this implementation because it produced the most efficient bytecode at the time I wrote the article. You can use this variant too, which is even more compact:

open class SingletonHolder<out T : Any, in A>(creator: (A) -> T) {
private var creator: ((A) -> T)? = creator

@Volatile
private var instance: T? = null

fun
getInstance(arg: A): T {
return instance ?: synchronized(this) {
instance
?: creator!!(arg).also {
instance
= it
creator
= null
}
}
}
}

--

--

Christophe Beyls
Christophe Beyls

Written by Christophe Beyls

Android developer from Belgium, blogging about advanced programming topics.

No responses yet