Skip to content

Instantly share code, notes, and snippets.

@markmaynard
Last active June 10, 2019 11:49
Show Gist options
  • Save markmaynard/f0893882a0d2cdf0d272645750bbdff7 to your computer and use it in GitHub Desktop.
Save markmaynard/f0893882a0d2cdf0d272645750bbdff7 to your computer and use it in GitHub Desktop.
Enum for class instantiation
interface ClassBackedEnum {
fun toClass(): Any
}
class ThingFactory private constructor() {
enum class ThingType(): ClassBackedEnum {
Thing1Type {
override fun toClass() = Thing1::class
},
Thing2Type {
override fun toClass() = Thing2::class
}
}
constructor (clazz: ThingType): this() {
if (myThing == null) {
when(clazz.toClass()) {
Thing1::class -> myThing = Thing1()
Thing2::class -> myThing = Thing2()
}
} else {
if (myThing?.javaClass?.kotlin != clazz.toClass()) {
throw RuntimeException("Already created as type:${myThing?.javaClass?.kotlin}")
}
}
}
fun run() {
myThing?.run()?: throw RuntimeException("Singleton not instantiated")
}
fun play() {
myThing?.play()?: throw RuntimeException("Singleton not instantiated")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment