Skip to content

Instantly share code, notes, and snippets.

@lmller
Created May 8, 2017 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmller/9f3cd142787ca81932bf0f121a05d3c3 to your computer and use it in GitHub Desktop.
Save lmller/9f3cd142787ca81932bf0f121a05d3c3 to your computer and use it in GitHub Desktop.
Reified generics kotlin.
//me playing around for https://kotlinlang.slack.com/archives/C0922A726/p1494235351616257
fun main(args: Array<String>) {
UnBundler.unbundlers.add(object: UnBundler(canHandle = Test::class) {
override fun unbundle(b: Bundle): Any {
println("it works!")
return Test()
}
})
TestTest()
}
inline fun <reified R: Bundler> Any.fromBundle(b: Bundle) : R {
return UnBundler.unBundle<R>(b)
}
class TestTest {
init {
//val test: NotTest = fromBundle(object: Bundle{}) // throws
val test: Test = fromBundle(object: Bundle{}) // works
}
}
abstract class UnBundler(val canHandle: KClass<*>) {
companion object {
val unbundlers: MutableList<UnBundler> = arrayListOf()
inline fun <reified R> unBundle(b: Bundle): R {
val unbundler = unbundlers.find { it.canHandleClass(R::class) }
if (unbundler == null)
throw UnBundlerNotRegistered()
return unbundler.unbundle(b) as R
}
}
fun canHandleClass(kClass: KClass<*>): Boolean {
return kClass == canHandle
}
abstract fun unbundle(b: Bundle): Any
}
interface Bundle
interface Bundler
class UnBundlerNotRegistered : Throwable() {
}
class Test: Bundler {
}
class NotTest: Bundler {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment