Using singleton objects in a ServiceLoader

I’ve just finished moving a part of the code to Kotlin and found that an object could not be used as a service in a ServiceLoader, since object could not be instantiated by ServiceLoader implementation.

I understand why it works this way and I can always return to using class without parameters instead of object, but maybe there is a better workaround, to keep it kotlinish?

That is more of an Android issue, just like you can’t instantiate an Activity yourself and it has to be created by the runtime (and for dependency injection it would be so nice to not have that restriction).

I’ve used a cheap workaround. Like that:


val xmlMetaType = XMLMetaType()

class XMLMetaType{...}

Also I thought about it a bit and decided that there is no easy way to solve it inside existing ServiceLoader toolset. In order to make objects loadable via reflections, one has to write his own kotlin specific service loader. It probably is an interesting task, but not of high priority for now.

For what it’s worth a temporary workaround would be using the following syntax:

interface MyInterface {
    fun myMethod() : String
}

object MyObject : MyInterface {
    override fun myMethod() : String = "hello"
}

class MyObjectServiceLoaderProxy : MyInterface by MyObject

And have MyObjectServiceLoaderProxy being exposed to ServiceLoader. This only works with interfaces as it relies on delegation, but it should cover most of the cases.

Having more automation around this would be fantastic though, Add support for Kotlin Objects as services for autoService · Issue #785 · google/auto · GitHub