madhead
madhead

Reputation: 33422

Koin nullable (optional) bean

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?

Upvotes: 1

Views: 3165

Answers (1)

Keyvan Norouzi
Keyvan Norouzi

Reputation: 159

I didn't find an official way that works. I solved my problem with this code snippet :

   val data: ClassModel? = try {
        get(named("YourNamedValue"))
    } catch (e: InstanceCreationException) {
        null
    } catch (e: IllegalStateException) {
        null
    }

Upvotes: 1

Related Questions