2

I know I can get all subclasses of a sealed class in Kotlin, but I'm looking for a way to get all implementations of an interface.

So instead of ...

sealed class HotDrinkFactory {
    abstract fun prepare(amount: Int): HotDrink
}

class TeaFactory : HotDrinkFactory() {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

class CoffeeFactory : HotDrinkFactory() {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

fun main(args: Array<String>) {
    val hotDrinkFactories = HotDrinkFactory::class.sealedSubclasses
    hotDrinkFactories.forEach { println(it::class.qualifiedName) }
}

... I would like to have

interface HotDrinkFactory {
    fun prepare(amount: Int): HotDrink
}

class TeaFactory : HotDrinkFactory {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

class CoffeeFactory : HotDrinkFactory {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

fun main(args: Array<String>) {
    val hotDrinkFactories = HotDrinkFactory::class.<<< Something here? >>>
    hotDrinkFactories.forEach { println(it::class.qualifiedName) }
}
Johan Vergeer
  • 5,208
  • 10
  • 48
  • 105
  • 2
    [This is not _really_ possible without some workarounds](https://stackoverflow.com/a/3123134/7366707); maybe rethinking the design would be a better idea. – Salem Dec 22 '18 at 21:08
  • @Moira Yeah, I already found that post, but I hoped there would be a way by now with Kotlin. – Johan Vergeer Dec 23 '18 at 08:07
  • What problem do you want to solve with that code? Sounds like a Service Provider Interface (SPI) could serve you well. https://docs.oracle.com/javase/tutorial/sound/SPI-intro.html – Simulant Dec 24 '18 at 08:54
  • @Simulant I'm building a console application, where I would like to get the class names and output them as options to the user. To be fair, this is just a practice project – Johan Vergeer Dec 24 '18 at 11:27

0 Answers0