Skip to content

Instantly share code, notes, and snippets.

@stellingsimon
Last active April 8, 2022 11:23
Show Gist options
  • Save stellingsimon/d39563d07ea9245c06e6fc904abfbe9a to your computer and use it in GitHub Desktop.
Save stellingsimon/d39563d07ea9245c06e6fc904abfbe9a to your computer and use it in GitHub Desktop.
import kotlin.reflect.KProperty1
import kotlin.reflect.full.declaredMemberProperties
// A `Catalog` is similar to an `enum class` in the sense that
// * every property is available through a static identifier
// * you can list the `values()`
// A `Catalog` is different from an `enum class` in the sense that
// * its properties are of a different type
// * you can distribute properties among several catalog objects
// A catalog is a static enumeration that is non-exhaustive.
// Example usage:
object CatalogA : Catalog<ComplexObject>() {
val first = ComplexObject(1, "first")
val second = ComplexObject(2, "second")
val oops = 42
}
object CatalogB : Catalog<ComplexObject>() {
val third = ComplexObject(3, "third")
val fourth = ComplexObject(4, "fourth")
}
// Implementation:
abstract class Catalog<T> {
@Suppress("UNCHECKED")
fun values(): Set<T> {
val catalog = checkNotNull(this::class.objectInstance)
return this::class.declaredMemberProperties.map {
val property = it as KProperty1<Any, T>
property.get(catalog)
}.toSet()
}
}
data class ComplexObject(
val id: Int,
val name: String,
)
fun caller() {
val complexObjects = CatalogA.values() + CatalogB.values()
println(complexObjects.joinToString(separator="\n"))
}
caller()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment