Oleg Shuliak
11/05/2022, 10:42 AMServiceInterface
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.
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?andylamax
11/05/2022, 10:47 AMI need to use one implementation or another based on some propertySince you need both implementations, you have to have them ready. Something in the lines of
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
}
}
Oleg Shuliak
11/05/2022, 10:53 AMval service1: ServiceInterface,
val service2: ServiceInterface
are the same type of ServiceInterface
, where the magic happens and service1
becomes ConcreteService1
?PoisonedYouth
11/05/2022, 11:08 AMOleg Shuliak
11/05/2022, 11:09 AM