Archie G. Quiñones
Archie G. Quiñones

Reputation: 13708

Provide an Instance as its interface in Koin

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?

Upvotes: 18

Views: 13722

Answers (3)

Songzhw
Songzhw

Reputation: 169

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

single<NumberClassifier> { Singleton.createClassifier() }
single<LetterClassifier> { Singleton.createClassifier() }

Upvotes: 0

Dima S
Dima S

Reputation: 649

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

Upvotes: 36

zsmb13
zsmb13

Reputation: 89658

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.

Upvotes: 6

Related Questions