gh-pages / com.nextfaze.devfun.inject / singletonInstance


inline fun <reified T : Any> singletonInstance(noinline instance: () -> T?): InstanceProvider (source)

Utility function to provide a single instance of some type.


class SomeType : BaseType

val provider = singletonInstance { SomeType() } // triggers for SomeType or BaseType (result of invocation is saved)

If you want to reduce the type range then specify its base type manually:

val provider = singletonInstance<BaseType> { SomeType() } // triggers only for BaseType (result of invocation is saved)

Be wary of using a typealias as a type - the resultant function “type” itself is used at compile time. e.g.

typealias MyStringAlias = () -> String?
val provider1 = singletonInstance<MyStringAlias> { ... }

typealias MyOtherAlias = () -> Type?
// will be triggered for MyStringAlias and MyOtherAlias since behind the scenes they are both kotlin.Function0<T>
val provider2 = singletonInstance<MyOtherAlias> { ... }

See Also