10/14/2021, 11:36 AM
If I have:
sealed interface Foo

object Bar : Foo

object Baz : Foo

fun <T : Foo> getFooObjects(): List<T> = TODO("How do I get this list?")
I think I got it:
fun <T : Foo> getFooObjects(): List<T> = Foo::class.sealedSubclasses.filterIsInstance<Table>()
That was wrong...
fun <T : Foo> getFooObjects(): List<T> = Foo::class.sealedSubclasses.mapNotNull { it.objectInstance }

Michael de Kaste

10/14/2021, 12:04 PM
the whole T : Foo typing is a bit weird. I get that what you want is only the sealed implementations of Foo, but Foo itself is of type Foo. It sounds like you want it generic? So maybe
inline fun <reified T> getObjectsOfType(): List<T> = T::class.sealedSubclasses.mapNotNull { it.objectInstance }
if not, simply
fun getFooObjects(): List<Foo> = Foo::class.sealedSubclasses.mapNotNull { it.objectInstance }
would do the trick


10/14/2021, 12:09 PM
I ended up with (for setting up the schemas in the db with exposed...) - the problem was that I can't inherit an interface from a class (Table) and takes in Tables...:
sealed interface DbTables

object Foos : IntIdTable("foo"), DbTables

val tables = DbTables::class.sealedSubclasses
                        .mapNotNull { kclass -> kclass.objectInstance as? Table }

                    SchemaUtils.drop(*tables, inBatch = true)
                    SchemaUtils.create(*tables, inBatch = true)
This whole thing was to avoid having to keep a separate list of tables that I might forget to add new tables to... having them inherit the sealed interface is the easiest way to see if that object was added...