3

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"))

2 Answers2

0

with

with is TypeBinder is type binding(via generic) with given tag & type (is required).

from

from is DirectBinder is direct binding with a given tag (not required type). It's will be defined type depend on type of factory.

The difference between each binder is just the way to type inference. thus, you can use a more efficient binder when declaring module.

Ethan Choi
  • 2,339
  • 18
  • 28
0

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.

Salomon BRYS
  • 9,247
  • 5
  • 29
  • 44