18

Lets say I have two interfaces like:

interface LetterClassifier
interface NumberClassifier

Then these interfaces would be applied to this class:

class Classifier() : LetterClassifier, NumberClassifier

Now, I want to provide these instances only as LetterClassifier and NumberClassifier and not as Classifier in Koin.

The way I think of doing this is by doing:

module {
    val classifier = Classifier()

    single<NumberClassifier> { classifier }
    single<LetterClassifier> { classifier }
}

But I don't think this is the right way. Can someone guide me?

Archie G. Quiñones
  • 11,638
  • 18
  • 65
  • 107

3 Answers3

32

You could bind types to your definition like it is described on official article:

single { Classifier() } binds arrayOf(LetterClassifier::class, NumberClassifier::class)

If you want to exclude Classifier type at all you could do something like:

single<LetterClassifier> { Classifier() } bind NumberClassifier::class
Dima S
  • 469
  • 5
  • 9
6

The way you're doing it is in fact the right way! Here's another example from the Koin docs, doing the same thing:

class DataRepository()
interface Presenter
class MyPresenter(val repository : Repository) : Presenter

val myModule = module {
    // Define a singleton for type  DataRepository
    single { DataRepository() }

    // Define a factory (create a new instance each time) for type Presenter (infered parameter in <>) 
    // Resolve constructor dependency with get()
    factory<Presenter> { MyPresenter(get()) }
}

One small thing to note when doing this: your approach immediately creates an instance at the time the module declaration is being processed, while placing the constructor calls in the single lambdas would create instances when needed:

single<NumberClassifier> { Classifier() }
single<LetterClassifier> { Classifier() }

Although this would create a separate single instance for both of the interfaces.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • But I the same Instance. It is possible to do so without immediately creating the instance? Or should I simply make the instantiation lazy so it would create it immediately? – Archie G. Quiñones Sep 06 '19 at 06:17
0

You can have a function or a Singleton to provide instance,

single<NumberClassifier> { Singleton.createClassifier() }
single<LetterClassifier> { Singleton.createClassifier() }
cigien
  • 57,834
  • 11
  • 73
  • 112
Songzhw
  • 131
  • 1
  • 3