what is the correct way of using delegation in the...
# announcements
r
what is the correct way of using delegation in the context of an object? I tried this but get a compilation error, factory must to be initialized:
Copy code
object CoreFactory : ICoreFactory by factory {
    private val factory: ICoreFactory

    init {
        val loader = ServiceLoader.load(ICoreFactory::class.java)
        val itr = loader.iterator()
        check(itr.hasNext()) {
            "Could not find an implementation for ${ICoreFactory::class.java.name}"
        }
        factory = itr.next()
    }
}
o
I would simply use lazy top-level property:
Copy code
val CoreFactory by lazy {
        val loader = ServiceLoader.load(ICoreFactory::class.java)
        val itr = loader.iterator()
        check(itr.hasNext()) {
            "Could not find an implementation for ${ICoreFactory::class.java.name}"
        }
        itr.next()
}
r
I think I would have never come up with this solution, thanks 🙂
o
Also since
ServiceLoader
implements
Iterable
, you might do this:
ServiceLoader.load(ICoreFactory::class.java).firstOrNull() ?: throw IllegalStateException("Could not find an implementation for ${ICoreFactory::class.java.name}")
Or
singleOrNull
if you want to constraint to only single implementation being available
r
actually I do (constrain it to a single implementation), thanks for the additional hint