pavankumar
02/03/2023, 4:01 PMNullPointerException
when calling createInstance()
method. Is there any solution to make it work
fun main() {
val a = A.getInstance()
println("value of ${a.num}")
}
class A {
val num: Int = 10
companion object : SingletonHolderWithoutArgs<A>(::createInstance) {
private fun createInstance(): A {
return A()
}
}
}
open class SingletonHolderWithoutArgs<out T>(private val func: () -> T) {
@Volatile
private var instance: T? = null
fun getInstance(): T =
synchronized(this) {
instance ?: func().also { instance = it }
}
}
Sam
02/03/2023, 4:10 PMA.createInstance
function inside A’s constructor, i.e. before A
has actually been initialised. Although A has been initialised by the time you call the function, the reference was created before that happened.Luke Armitage
02/03/2023, 4:11 PMpavankumar
02/03/2023, 4:12 PMinline
keyword before createInstance
method then problem is solved but I don't know why inline
keyword fixes the problem.Sam
02/03/2023, 4:14 PMA
an object
?fun main() {
val a = A
println("value of ${a.num}")
}
object A {
val num: Int = 10
}
mkrussel
02/03/2023, 4:19 PMlazy
delegate.pavankumar
02/03/2023, 4:20 PMinternal class Starter private constructor(
initializer: Initializer,
creator: Creator,
unlocker: Unlocker
) : Initializer by initializer,
Creator by creator,
Unlocker by unlocker {
companion object :
SingletonHolderWithoutArgs<Starter>(Starter::createInstance) {
private inline fun createInstance(): Starter {
val job = Components.from(AComponent::class.java).Job()
return Starter(
SdkDataVaultInitializerImpl(job),
SdkDataVaultCreatorImpl(job),
SdkDataVaultUnlockerImpl(job)
)
}
}
}
mkrussel
02/03/2023, 4:21 PMclass A {
val num: Int = 10
companion object {
val instance by lazy { A() }
}
}
fun main() {
val a = A.instance
println("value of ${a.num}")
}
Starter
as an object class.
Are these singleton holders are not needed (they weren't really need in Java either)createInstance
function just becomes your init
block.pavankumar
02/03/2023, 4:26 PMcreateInstance()
with init
block then i'm making my class not easily testable right?
What i mean is the private constructor
can be @VisibleForTesting constructor(...)
in future. So init
block might give me trouble at that time.Luke Armitage
02/03/2023, 4:38 PMKevin Del Castillo
02/03/2023, 5:32 PM@Volatile
is useless