Last active
June 10, 2019 11:49
-
-
Save markmaynard/f0893882a0d2cdf0d272645750bbdff7 to your computer and use it in GitHub Desktop.
Enum for class instantiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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