Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide an Instance as its interface in Koin

Tags:

kotlin

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?

like image 394
Archie G. Quiñones Avatar asked Sep 06 '19 06:09

Archie G. Quiñones


2 Answers

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
like image 86
Dima S Avatar answered Oct 10 '22 23:10

Dima S


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.

like image 29
zsmb13 Avatar answered Oct 10 '22 23:10

zsmb13