Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"bind" method is not type-safe #1028

Closed
qwert2603 opened this issue Mar 1, 2021 · 0 comments · Fixed by #1227
Closed

"bind" method is not type-safe #1028

qwert2603 opened this issue Mar 1, 2021 · 0 comments · Fixed by #1227

Comments

@qwert2603
Copy link
Contributor

qwert2603 commented Mar 1, 2021

Describe the bug
bind extension method of BeanDefinition is not type-safe and can lead to runtime error, though it could be checked in compile-time in some cases.

To Reproduce

import org.koin.core.context.GlobalContext
import org.koin.core.context.startKoin
import org.koin.dsl.bind
import org.koin.dsl.module
import org.koin.test.check.checkModules

fun main() {
    val module = module {
        single { "the_string" }.bind<Int>()
    }

    checkModules {
        modules(module) // this won't help
    }

    startKoin {
        modules(module)
    }

    val koin = GlobalContext.get()

    println(koin.get<String>())
    println(koin.get<Int>()) // ClassCastException
}

Expected behavior
It would be great to move such errors to compile-time.

Koin project used and used version:
koin_version = "2.2.2"

Possible solution

Type-safety may be achieved by using the following declaration, that specifies the base type explicitly:

infix fun <B : Any, T : B> BeanDefinition<T>.bindSafe(clazz: KClass<B>): BeanDefinition<T> {
    secondaryTypes = secondaryTypes + clazz
    return this
}

But there is a bind method, that doesn't take KClass argument and I didn't found yet an easy way to make it safe.

inline fun <reified T> BeanDefinition<*>.bind(): BeanDefinition<*> {
    return bind(T::class)
}

We can make the following:

inline fun <reified B : Any, T : B> BeanDefinition<T>.bindSafe(): BeanDefinition<T> {
    return bind(B::class)
}

But the usage of this in verbose:

single { "the_string" }.bindSafe<CharSequence, String>()

So this improvement is the subject for discussion.
I can make PR, if this solution will find support from community.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant