Home:ALL Converter>Koin nullable (optional) bean

Koin nullable (optional) bean

Ask Time:2019-08-16T23:27:17         Author:madhead

Json Formatter

I want to have a nullable bean in my koin application, like:

single(named("NULLABLE")) {
    System.getenv("NULLABLE")
}

I.e. if the environment variable "NULLABLE" is set, then a bean (a string here) named "NULLABLE" will have its value, otherwise it will be null.

The usage could be like:

init {
    startKoin {
        modules(listOf(module))
    }
}

val nullableString: String? by inject(named("NULLABLE"))

However, if there is no environment variable named "NULLABLE" I get the exception:

Exception in thread "main" java.lang.IllegalStateException: Single instance created couldn't return value
    at org.koin.core.instance.SingleDefinitionInstance.get(SingleDefinitionInstance.kt:42)
    at org.koin.core.definition.BeanDefinition.resolveInstance(BeanDefinition.kt:70)
    at org.koin.core.scope.Scope.resolveInstance(Scope.kt:165)
    at org.koin.core.scope.Scope.get(Scope.kt:128)

It's because currently a SingleDefinitionInstance throws an exception when the factory lambda returned null:

override fun <T> get(context: InstanceContext): T {
    if (value == null) {
        value = create(context)
    }
    return value as? T ?: error("Single instance created couldn't return value")
}

Is it possible to have a nullable (optional) beans in Koin?

Author:madhead,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/57527303/koin-nullable-optional-bean
yy