hey everyone. I’ve got a question about interfaces...
# getting-started
o
hey everyone. I’ve got a question about interfaces. I can’t yet understand the best way of how to decide which concrete implementation of interface to use. Let’s imagine, that I have
ServiceInterface
that has 2 implementations
ConcreteService1
and
ConcreteService2
It’ll have one function
doWork()
. I need to use one implementation or another based on some property, that comes as a parameter. And I don’t understand where do I resolve which concrete class to use.
Copy code
class SomeClass(
    val someService: ServiceInterface
) {
    fun someFunction(status: String) {
        when(status) {
            "ACTIVE" -> someService.doWork() // or even better to return the instance of service
            "INACTIVE" -> someService.doWork()
        }
    }
}
Could someone give a hint?
1
a
Looks like you have the answer in your question.
I need to use one implementation or another based on some property
Since you need both implementations, you have to have them ready. Something in the lines of
Copy code
class SomeClass(
    val service1: ServiceInterface,
    val service2: ServiceInterface
) {
    fun someFunction(status: String) {
        val service: ServiceInterface = when(status) {
            "ACTIVE" -> service1
            "INACTIVE" -> service2
        }

        service.doWork() // you can return this service if that what you wanted
    }
}
o
ok, that makes sense. but if
Copy code
val service1: ServiceInterface,
    val service2: ServiceInterface
are the same type of
ServiceInterface
, where the magic happens and
service1
becomes
ConcreteService1
?
p
You either use a dependency injection framework, which is providing the correct instance or you need a kind of factory, which returns the concrete service depending on some custom logic
o
ok, got it. thanks a lot so explanation!