While studying about kodein i often see bind() with and bind() from.
Can anyone please tell me what is the difference and why are we using it.
Ex:
bind<Dice>() with provider { RandomDice(0, 5) }
bind<DataSource>() with singleton { SqliteDS.open("path/to/file") }
bind() from singleton { RandomDice(6) }
bind("DnD20") from provider { RandomDice(20) }
bind() from instance(SqliteDataSource.open("path/to/file"))
bind<Type>() with
defines Type
explicitly. This is important when you are, for example, binding an interface type to an implementation of it:
bind<Type>() with singleton { TypeImpl() }
Now consider that you are binding a a very simple type, such as a configuration data object:
bind<Config>() with singleton { Config("my", "config", "values") }
You've written Config
twice: once in the bind definition, and once in the bind itself.
Enter bind() from
: it does not define a type but leaves the choice of the bound type to the binding itself. The bound type is defined implicitly. For example, you could write the Config
binding as such:
bind() from singleton { Config("my", "config", "values") }
Note that binding a type to itself (which is what bind() from
is for) is often a bad idea (it goes against the IoC pattern) and should only be used for very simple types such as data classes.