Factory methods convention: classOf or .toClass?

Hi everyone,

I’m writing a small library that might be used by other developers and I’m facing some doubts how to design integration of this library with 3rd party code (in my case, Dagger DI).

For example, I want to provide interoperability with one or a Set of javax.inject.Provider and for that, I want to convert it to MyFactory. Looking at the standard library I found two ways of doing it:

  1. Create a .toMyFactory extension function for a Provider and a Set<Provider> which returns a MyFactory instance.
  2. Create a myFactoryOf which receives as parameter a Provider or a Set<Provider and builds a MyFactory instance.

Code sample:

fun test(provider: Provider<MyClass>, providers: Set<Provider<MyClass>>) {
    // Using `.toMyFactory`
    val fromInstance1 = provider.toMyFactory()
    val fromSet1 = providers.toMyFactory()

    // Using `myFactoryOf`
    val fromInstance2 = myFactoryOf(provider)
    val fromSet2 = myFactoryOf(providers)
}

What option is more Kotlin-friendly to provide this type of integration?

The extension method pattern tends to be favored in Kotlin.

See: toList, asExecutor

I’ve not seen any explicit convention but “to” seemed to be used in cases where data is copied, while “as” is used when an instance is wrapped. So I think asMyFactory would be the way to go.

There’s also methods like listOf, but they tend to be only used with vararg scenarios from what I’ve seen.

6 Likes