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

captureInstance

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

Utility function to capture an instance of an object.

e.g.

class SomeType : BaseType

val provider = captureInstance { someObject.someType } // triggers for SomeType or BaseType

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

val provider = captureInstance<BaseType> { someObject.someType } // triggers only for BaseType

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 = captureInstance<MyStringAlias> { ... }

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

See Also

singletonInstance

CapturingInstanceProvider